A C++;类函数 一个简单的C++文件和TT类有两种方法。 #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){ TT tt("First"); tt.Read("Hello", 12); return 1; }

A C++;类函数 一个简单的C++文件和TT类有两种方法。 #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){ TT tt("First"); tt.Read("Hello", 12); return 1; },c++,class,C++,Class,与 大体上 G++说: new.cc:31:错误:对“TT::Read(const char[5])的调用没有匹配的函数 为什么G++找不到Read(conststring&key)const方法 谢谢 您试图定义一个返回T的函数: template<class T> T TT::Read(const string& key) const { std::cout << key << std::endl; return 1; } 或者删

大体上

G++说:

new.cc:31:错误:对“TT::Read(const char[5])的调用没有匹配的函数

为什么G++找不到Read(conststring&key)const方法


谢谢

您试图定义一个返回T的函数:

template<class T>
T TT::Read(const string& key) const
{
    std::cout << key << std::endl;
    return 1;
}

或者删除模板定义,因为它在这里没有意义。

您的函数
templateT Read(const string&key)const在类型T上模板化,但T仅显示为返回类型

如果您打算手动将返回类型烘焙到函数中(看起来好像是从
return1;
的外观开始),则可以将声明更改为类似以下内容:

int Read(const string& key) const;
否则,必须在调用中手动指定模板类型,如下所示:

tt.Read<int>("Hello");

我相信这是因为在处理模板时,编译器希望知道返回函数是什么,即使它返回的是1,它也无法理解它。从技术上讲,返回1可能是错误的,因为它不知道返回值应该是什么


使用
tt.Read(“Hello”)

它刚刚在G++4.7上运行。2@billz,这对我来说是失败的:你只是说了我的答案,但更多的话+1带有参数的版本允许编译器自动派生模板参数
T
;如果没有参数,则必须显式地指定模板类型。
tt.Read<int>("Hello");
int Read(const string& key) const;
tt.Read<int>("Hello");
template<class X, class Y> X f(Y);

int i = f<int>(5.6); // Y is deduced to be double
int j = f(5.6); // ill-formed: X cannot be deduced