检查父构建器是否具有参数
Check if parent constructor has parameters
我有此代码:
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() {}
};
相关文章:
- 在C++中,使用带有 std::optional 参数的函数<T>来表示可选参数是否有意义?
- 如何检查给定的参数是否为 cv::noArray()?
- 如果返回 -1,时间() 的参数是否被修改?
- C++中大多数/所有 setter 函数的参数是否应该写为常量引用?
- 检查两个模板参数是否相同
- 空函数的参数是否加载到缓存中?
- 使用 lambda 作为构造函数参数是否需要C++ 17?
- 了解'this'或其他参数是否为右值
- const-ref传递的模板化参数是否经过优化,以便在足够小时按值传递
- shared_ptr构造函数参数是否应按值传递
- 如何检查模板参数是否为给定值?
- 使用聚合初始化模拟默认函数参数是否存在任何陷阱?
- 在对象序列化期间添加额外参数是否有更好的方法?
- 通过 ssh 发送参数.是否有非阻塞输入函数?
- 如何检查运算符 != 模板参数是否存在 C++ 17?
- 常量引用函数参数:是否可以禁止临时对象?
- 如何检查模板参数是否为 std::variant?
- 是否可以确定函数的参数是否已签名或无符号,以实现可能性超载函数
- 移动 l 值参考参数是否是一种不好的做法?
- 显式指定通用 lambda 的 operator() 模板参数是否合法?