C++ 我如何专门为一个或某些情况使用析构函数?
我可以为一种情况专门使用析构函数,但我很难告诉编译器在任何其他情况下只使用普通析构函数:C++ 我如何专门为一个或某些情况使用析构函数?,c++,templates,destructor,template-specialization,C++,Templates,Destructor,Template Specialization,我可以为一种情况专门使用析构函数,但我很难告诉编译器在任何其他情况下只使用普通析构函数: #include <iostream> template <int = 0> struct Foo { ~Foo(); }; int main() { { Foo<> a; // Normal destructor called } { Foo<7> a; // Special destru
#include <iostream>
template <int = 0>
struct Foo
{
~Foo();
};
int main()
{
{
Foo<> a; // Normal destructor called
}
{
Foo<7> a; // Special destructor called
}
}
template<>
Foo<7>::~Foo() { std::cout << "Special Foo"; }
template<>
Foo<>::~Foo() {} // Normal destructor does nothing.
这很好,但是现在如果我添加另一个模板参数,例如fooa;然后链接器说它找不到析构函数定义。我怎么能说我想要一个只针对7号的特殊析构函数,然后用一个普通的析构函数处理任何其他情况呢
我试过:
Foo::~Foo() {} // Argument list missing
Foo<int>::~Foo() {} // Illegal type for non-type template parameter
template<>
Foo<int>::~Foo() {} // Same thing
template<int>
Foo<>::~Foo() {} // Function template has already been defined
我怎么能说我想要一个只针对7号的特殊析构函数,然后用一个普通的析构函数处理任何其他情况呢
一般析构函数应定义为:
template <int I>
Foo<I>::~Foo() { std::cout << "general dtor"; }
非常非常甜蜜,谢谢。它们可以像普通/未模板类函数一样在类本身内联定义吗?我已经接受了你的答案,但我很难像你说的那样在类本身中定义它。如果不太麻烦的话,您可以在Foo struct inline中给出一个定义的快速片段吗?代码已经在你提供的实时链接中设置好了。
template<>
Foo<>::~Foo() {} // Normal destructor does nothing.
template<>
Foo<0>::~Foo() {}