共有三个文件:
主.cpp:
#include "test.h"
int main()
{
A<int> ai;
ai.print();
A<double> ad;
ad.print();
A<char> ac;
ac.print();
return 0;
}
测试.cpp:
#include <iostream>
#include "test.h"
template<typename Type>
void A<Type>::print()
{
std::cout << "some" << std::endl;
}
//template<>
//class A<int>
//{
//public:
// void print()
// {
// std::cout << "int" << std::endl;
// }
//};
template class A<int>;
template class A<double>;
template class A<char>;
测试.h:
#ifndef TEST_H
#define TEST_H
template<typename Type>
class A
{
public:
void print();
};
#endif
显示:
some
some
some
我想对类模板进行明确的专业化A,为此我将取消注释注释行。结果:
/usr/bin/ld: /tmp/cc5Vvv83.o: in function `main':
/home/ivan/first/main.cpp:6: undefined reference to `A<int>::print()'
collect2: error: ld returned 1 exit status
如果我复制这个定义并将其移动到标题中,那么程序将运行并给出它需要的内容:
int
some
some
但我不想把方法定义A<int>::print()放在标题中,所以我test.h把它留在:
template<>
class A<int>
{
public:
void print();
};
test.cpp我把:
template<>
void A<int>::print()
{
std::cout << "int" << std::endl;
}
结果:
test.cpp:11:6: error: template-id ‘print<>’ for ‘void A<int>::print()’ does not match any template declaration
11 | void A<int>::print()
| ^~~~~~
In file included from test.cpp:2:
test.h:15:14: note: candidate is: ‘void A<int>::print()’
15 | void print();
| ^~~~~
问题: 1)在这种情况下,如何将类的定义保留在A<int>中test.h,将方法的定义保留A<int>::print()在and 中test.cpp,以便程序可以工作?2)处理这种情况的正确方法是什么?也许我们应该把定义留在头文件中而不用打扰(尽管据我所知,这样我们会增加编译时间)?
三点:
A<int>,这不是必需的: