【发布时间】:2018-03-16 15:17:48
【问题描述】:
我可以针对一种情况专门使用析构函数,但我无法告诉编译器对任何其他情况只使用普通析构函数:
#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 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
【问题讨论】:
标签: c++ templates destructor template-specialization