检查父构建器是否具有参数

Check if parent constructor has parameters

本文关键字:参数 是否 构建 检查      更新时间:2023-10-16

我有此代码:

template<class T>
class StackException: public T {
    public:
        StackException(const char* msg): T(msg) {} //<---problem here
}
template<class T>
void myThrow(const &T e) {
    throw StackException<T>(e.what());
}

此代码适用于具有哪种方法的通用异常,但有时我的代码中的异常是在构造函数中没有任何参数的情况下定义的。我需要一种方法来启用/禁用根据母体构造函数启用stackexception的构造函数。我该如何使用Sfinae做到这一点?我正在使用C 11。

您可以通过std::is_constructible进行专业化。您必须专业化整个班级,您不能仅部分专业构造函数

template<class T, class = std::is_constructible<T, const char *>>
class StackException;
template<class T>
class StackException<T, std::true_type> : public T {
public:
    StackException(const char* msg): T(msg) {} // no problem anymore
};
template<class T>
class StackException<T, std::false_type> : public T {
public:
    StackException(const char* msg): {} // no problem anymore
};

但是,您可能会发现仅复制T,而不是what

更容易
template<class T>
class StackException : public T {
public:
    StackException(const T & t): T(t) {} // no problem anymore
};
template<class T>
void myThrow(const &T e) {
    throw StackException<T>(e);
}

std::is_constructible是您需要区分情况所需的特征。然后,您可以使用Sfinae,专业化或标签调度。

以下示例使用委托构造函数的标签调度:

template<class T>
class StackException: public T {
public:
    StackException(const char* msg) :
         StackException(msg, std::is_constructible<T, const char *>{})
    {}
private:
    StackException(const char* msg, std::true_type): T(msg) {}
    StackException(const char* msg, std::false_type): T() {}
};