【问题标题】:How can I specialise a destructor for just one case, or some cases?我怎样才能将析构函数专门用于一种情况或某些情况?
【发布时间】: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


    【解决方案1】:

    我怎么能只说我想要一个仅用于数字 7 的特殊析构函数,并使用普通析构函数处理任何其他情况?

    一般的析构函数应该定义为:

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

    对于

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

    因为模板参数有一个默认值0,所以上面的代码只是Foo&lt;0&gt;的特化,就像你为Foo&lt;7&gt;做的一样。相当于

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

    LIVE

    【讨论】:

    • 非常非常甜蜜,谢谢。它们可以像普通/非模板类函数一样在类本身中内联定义吗?
    • 我已经接受了你的回答,但我无法像你说的那样在课堂上定义它。如果不是太麻烦,您能否在 Foo 结构内联中快速给出一个定义的 sn-p ?代码已在您提供的 LIVE 链接中设置。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-01
    • 1970-01-01
    • 2013-09-14
    • 1970-01-01
    • 2018-02-20
    • 2023-01-24
    相关资源
    最近更新 更多