【发布时间】:2017-10-15 03:20:28
【问题描述】:
这是我之前的question 的后续。
我有一个对任何东西都有强制转换运算符的类。在 C++17 之前的环境中,这会产生在执行初始化时无法选择适当的构造函数重载的错误。我想通过为某些类型标记强制转换运算符explicit 来调整行为。但是,我找不到这样做的方法。
这是一个人为的例子:我想要一个对整数类型的隐式转换运算符和对所有其他类型的显式转换。
这不起作用,因为我们无法确定 U 具有 typename std::enable_if<!std::is_integral<U>::value, U>::type 类型的表达式:
struct C {
template<typename U>
operator typename std::enable_if< std::is_integral<U>::value, U>::type() const {
return 1;
}
template<typename U>
explicit operator typename std::enable_if<!std::is_integral<U>::value, U>::type() const {
return 1.5;
}
};
这个编译失败说C::operator U() cannot be overloaded:
struct C {
template<typename U, typename = typename std::enable_if< std::is_integral<U>::value, U>::type>
operator U() const {
return 1;
}
template<typename U, typename = typename std::enable_if<!std::is_integral<U>::value, U>::type>
explicit operator U() const {
return 1.5;
}
};
我不能声明 template<typename U, typename = void> operator U(); 类型的函数并对其进行部分特化,因为不允许部分函数特化,而且创建辅助类对我来说似乎有点过头了。
如何根据我要转换的类型的某些特征声明转换运算符?
我需要一个 C++11 解决方案,因为在 C++17 中,我之前的问题中的问题已经是 resolved.b
【问题讨论】:
标签: c++ casting template-meta-programming sfinae