在enabled-if类中析构函数的脱行定义

out of line definition for destructor in enabled-if class?

本文关键字:定义 析构函数 enabled-if      更新时间:2023-10-16

如何为带有std::enable_if参数的模板类编写行外析构函数体?

(我需要它来编写一个装饰器,为其他对象类型添加一个标识符)。

代码:

template<typename T,
typename std::enable_if<std::is_base_of<X,T>::value>::type* = nullptr>
class IdentifiedInstance: public T
{
public:
    virtual ~IdentifiedInstance() = 0; // abstract base, still needs a function body
};
身体定义:

template<typename T,
typename std::enable_if<std::is_base_of<X,T>::value>::type* = nullptr>
IdentifiedInstance::~IdentifiedInstance()
{
}

不能编译,因为IdentifiedInstance::应该是IdentifiedInstance<T, ???>::

这里的第二个参数值是什么?我该怎么写呢?

笔记(1):

Visual Studio 2015接受以下格式:

template<typename T,
typename std::enable_if<std::is_base_of<X,T>::value>::type* = nullptr>
class IdentifiedInstance: public T
{
public:
    ~IdentifiedInstance() = 0
    {
    }
};

不幸的是,我写的代码也需要在linux下构建(并且gcc正确地阻塞了这种形式)。

注释(2):我试着在网上搜索这个,但是我发现的大多数答案都是关于如何部分专门化析构函数。

这个怎么样?

template<typename T,
typename std::enable_if<std::is_base_of<X,T>::value>::type* S>
IdentifiedInstance<T,S>::~IdentifiedInstance()
{
}

只命名第二个参数。

我还删除了默认值,因为您可能不会两次给出默认值(声明和定义)。