我可以为一种情况专门化一个析构函数,但我无法告诉编译器仅对任何其他情况使用普通的析构函数:
#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.
这工作正常,但现在如果我添加另一个模板参数,例如 Foo<3> a;然后链接器说它找不到析构函数定义。我怎么能说我想要一个仅用于数字 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
最佳答案
How can I just say I want a special destructor just for number 7, and handle any other cases with a normal destructor?
一般析构函数应定义为:
template <int I>
Foo<I>::~Foo() { std::cout << "general dtor"; }
对于
template<>
Foo<>::~Foo() {} // Normal destructor does nothing.
因为模板参数有一个默认值0
,所以上面的代码只是 Foo<0>
的特化,就像您对 Foo<7>
所做的那样。相当于
template<>
Foo<0>::~Foo() {}
关于c++ - 如何将析构函数专门用于一种情况或某些情况?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46578247/