【发布时间】:2014-01-31 01:02:45
【问题描述】:
我是使用 c++ 模板编程的新手。我有 3 个代码文件
main.cpp
#include "template_test.h"
#include <iostream>
using namespace std;
int main()
{
mytest<int> mt;
mt.method(1);
system("pause");
return 0;
}
template_test.h
#include <iostream>
using namespace std;
template<class T>
class mytest
{
public:
void method(T input){}
};
template<>
void mytest<int>::method(int input)
{
cout << "ok" << endl;
}
template_test.cpp
#include "template_test.h"
//empty
代码在VS2013中生效。但是,当我将代码更改为 2 种情况时,我的代码都有问题。
1.第一个是链接器错误码。
main.cpp
#include "template_test.h"
#include <iostream>
using namespace std;
int main()
{
mytest<int> mt;
mt.method(1);
system("pause");
return 0;
}
template_test.h
#include <iostream>
using namespace std;
template<class T>
class mytest
{
public:
void method(T input);
};
template<class T>
void mytest<T>::method(T input)
{
cout << " " << endl;
}//explicit specialization here
template<>
void mytest<int>::method(int input)
{
cout << "ok" << endl;
}
template_test.cpp
#include "template_test.h"
//empty
2.第二个输出什么都没有,而不是正确答案'ok'。
main.cpp
#include "template_test.h"
#include <iostream>
using namespace std;
int main()
{
mytest<int> mt;
mt.method(1);
system("pause");
return 0;
}
template_test.h
#include <iostream>
using namespace std;
template<class T>
class mytest
{
public:
void method(T input){}
};
template_test.cpp
#include "template_test.h"
template<>
void mytest<int>::method(int input)
{
cout << "ok" << endl;
}//move from .h to .cpp file here
c++ 模板的奇怪行为让我很困惑。那么,有什么问题呢?
【问题讨论】:
-
这里回答了第二个问题:stackoverflow.com/questions/15061774/… 第一个问题,你得到的链接器错误是什么?
-
@jogojapan VS2013 报告 LNK2005 和 LNK1169 代码
-
为什么你有一个
template_test.cpp只包含template_test.h(因此给该翻译单元它自己的模板函数副本)?您是否尝试过简单地删除该文件? -
@cHao
template_test.cpp只是第二种情况的例子。我将一些代码从 .h 文件移动到 .cpp 文件。对于前一种情况是没用的。 -
@jogojapan 啊,你是对的。