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

Viewed 59

I can specialise a destructor for one case, but I'm having trouble telling the compiler to just use a normal destructor for any other 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.

This works fine, but now if I add another template argument, for example Foo<3> a; then the linker says that it can't find the destructor definition. How can I just say I want a special destructor just for number 7, and handle any other cases with a normal destructor?

I tried:

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
1 Answers

How can I just say I want a special destructor just for number 7, and handle any other cases with a normal destructor?

The general destructor should be defined as:

template <int I>
Foo<I>::~Foo() { std::cout << "general dtor"; }

For

template<>
Foo<>::~Foo() {}    // Normal destructor does nothing.

Because the template parameter has a default value 0, so the above code is just a specialization of Foo<0>, just like what you did for Foo<7>. It's equivalent with

template<>
Foo<0>::~Foo() {}

LIVE

Related