Template, Return value, Type match

昨天遇到一个关于Template 和参数类型匹配的问题,Mark 一下。

源码:

#include <map>

#include <string>

#include <iostream>

 

using namespace std;

 

class TT{ 

public:

    TT(const string& str);

    template<class T>T Read(const string& key)const;

    template<class T>T Read(const string& key, const T& value)const;

};

 

TT::TT(const string& str){

    cout<<str<<endl;

}

 

template<class T>T TT::Read(const string& key)const{

    std::cout<<key<<std::endl;

    return 1;

}

 

template<class T>T TT::Read(const string& key, const T& value)const{

    std::cout<<key<<'\t'<<value<<std::endl;

    return value;

}

 

int main(void){

    int i;

    string str;

 

    TT tt("First Blood");

    i = tt.Read("Hello world!");

    

    return 1;

}

运行提示找不到对应的参数:

new.cc: In function ‘int main()’:
new.cc:43: error: no matching function for call to ‘TT::Read(const char [13])’

一般找不到对应的函数或者是定义的不是类函数,或者调用的时候参数不对,然后在stackoverflow 提问:http://stackoverflow.com/questions/13576845/a-c-class-function 说是Read 中返回参数有问题,应该是template<class T> 类型的才可以,于是修改Read() 函数为:

template<class T>T TT::Read(const string& key)const{

    std::cout<<key<<std::endl;

    T value = 1;

    return value;

}

依旧提示函数类型不对,最后发现是自己template 类型没有弄清楚,template<class T> 在一旦赋值后,类型就确定了,当T value = 1 时候,T 就已经成为int 类型,这样返回的是int 类型从而冲突。这样的错误仅在编译的时候看不出来的。

Template, Return value, Type match》上有4条评论

  1. 这个main 是没有确定T 的类型,
    我之前没看到class 中Read 函数有问题,
    templateT TT::Read(const string& key)const{
    std::cout<<key<<std::endl;
    return 1;
    }
    中return 1,将T 类型确定为int 类型(返回类型为int),这样在main 中Read 就找不到对应的类型调用

回复 dullgull 取消回复

您的电子邮箱地址不会被公开。 必填项已用*标注

此站点使用Akismet来减少垃圾评论。了解我们如何处理您的评论数据