c++ - 使用模板时的编译错误

标签 c++

template <class T>
class Test
{
public:
 template<class T>
 void f();  //If i define function here itself, error is not reported.
};

template <class T>
void Test<T>::f() 
{
}              //Error here.

int main()
{
 Test<float> ob;
 ob.f<int>();
}

它产生以下错误。

error C2244: 'Test<T>::f' : unable to match function definition to an
existing declaration

定义'void Test::f(void)'
现有声明 'void Test::f(void)'

错误说声明和定义具有相同的原型(prototype)但不匹配。 为什么这是一个错误?以及如何解决?

如果我在类中定义函数,它不会报告错误。 但我想在类外定义。

最佳答案

改变为

template <class T> 
class Test 
{ 
public: 
 template<class U> 
 void f(); 
}; 

template <class T> 
template<class U>
void Test<T>::f()  
{ 
} 

关于c++ - 使用模板时的编译错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4061741/

相关文章:

C++ 将 UTF8 字符数组转换为 CP1250

c++ - 如何在动态库(/MD)项目中使用静态库(/MT)?

c++ - 无法从谷歌 Protocol Buffer 编译示例

c++ - 如何在 C++ 中读取 Cyrillic Unicode 文件?

c++ - 在 apache 2.2 中正确使用 ap_set_content_type()

c++ - 在Linux中使用MYSQL.h编译C++程序

c++ - 这个内存屏障是否正确实现?

c++ - 具有 "placeholder"值的宏

c# - 您会使用什么语言在内存棒上实现自动更新/同步功能?

c++ - 如何从字符串开头提取子字符串到第二个定界符?