c++ - 如何将析构函数专门用于一种情况或某些情况?

标签 c++ templates destructor template-specialization

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

#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

关于c++ - 如何将析构函数专门用于一种情况或某些情况?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46578247/

相关文章:

c++ - 模板元编程 - 使用 Enum Hack 和 Static Const 的区别

c++ - 如何初始化作为类成员的数组?

c++ - 从内部类型参数推导出外部类型

shared-libraries - 共享库以什么顺序初始化和完成?

c++ - 构造函数和析构函数的调用顺序?

c++ - 我不知道为什么重复调用 OnDraw() 函数

c++ - Qt 应用程序 : Simulating modal behaviour (enable/disable user input)

c++ - "no matching function call to ' 使用 Android NDK 编译时绑定(bind) '"

html - 更改没有 body.background 的自定义博主模板中的背景

c++ - 在循环内部创建的返回变量导致析构函数被调用两次