当我不专注于构造函数(而是使用其他方法)时,一切都很好:
Test.h:
struct Type_1 {};
struct Type_2 {};
template<typename Type>
class Test {
public:
Test();
~Test();
void print();
}
Test.cpp的:
template<typename Type>
Test<Type>::Test() {}
template<typename Type>
Test<Type>::~Test() {}
template<>
Test<Type_1>::print(){ // Type_1 specific print }
template<>
Test<Type_2>::print(){ // Type_2 specific print }
效果很好,只要模板是Type_1或Type_2,他就会创建类,并相应地调用print()。
但如果我尝试专门构建构造函数,他说&#34;未定义对析构函数的引用&#34;但是析构函数应该自动推断出参数类型吗?
Test.cpp改变了:
template<>
Test<Type_1>::Test(){ // constructor when Type_1 }
template<>
Test<Type_2>::Test(){ // constructor when Type_2 }
template<typename Type>
Test<Type>::~Test(){ // should work for all right? }
我的问题是:如果我模板专门化一个构造函数,我是否必须专门化析构函数,即使它对所有人都相同?还有另一种方式吗?
提前感谢。
答案 0 :(得分:2)
不,您不需要定义任何成员函数的专用版本。你可以这样做:
template<typename Type>
class Test {
public:
Test();
~Test()
{
std::cout << "Default Dtor called." << std::endl;
}
void print();
};
//! These should go either in the class declaration or in a separate ipp/inl file.
//! You can put these in a .cpp if you use extern templates, but they might not be
//! supported on your compiler.
//! NOTE: If you use ipp/inl or declare these in the header but still outside the
//! class declaration, be sure to use inline on the member function definitions.
struct Type_1{};
struct Type_2{};
template <>
inline Test<Type_1>::Test()
{
std::cout << "Type_1 Ctor called" << std::endl;
}
template <>
inline Test<Type_1>::~Test()
{
std::cout << "Type_1 Dtor called" << std::endl;
}
template <>
inline Test<Type_2>::Test()
{
std::cout << "Type_2 Ctor called" << std::endl;
}
int main()
{
{
Test<Type_1> t1;
}
{
Test<Type_2> t2;
}
}
输出:
Type_1 Ctor叫
Type_1 Dtor叫
Type_2 Ctor叫
默认Dtor叫。
按任意键继续。 。