我怎样才能专门针对一种情况或某些情况的析构函数?

How can I specialise a destructor for just one case, or some cases?

我可以为一种情况特化析构函数,但我无法告诉编译器只对任何其他情况使用普通析构函数:

#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() {}

LIVE