当我不专门化构造函数(而是其他方法)时,一切都很好:
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()。
但是如果我尝试专化构造函数,他说"对析构函数的未定义引用",但是析构函数应该自动推断参数类型,对吗?
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? }
我的问题是:如果我模板专门化一个构造函数,我必须专门化的析构函数,以及,即使它是相同的?还有别的办法吗?
不需要定义任何成员函数的专门化版本。你可以这样做:
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医生呼叫
Type_2函数调用
Default doctor called.
按任意键继续…