当 Type = bool 时,运算符 bool() 与模板 Type() 运算符冲突
Operator bool() conflicting with template Type() operator when Type = bool
当模板类型为 bool 时,我的模板运算符与 bool 运算符冲突(重载(。有什么办法可以解决这个问题吗?例如,当 T 分配给布尔值时,我可以以某种方式"关闭"operator T()
吗?
template <typename T = bool>
class MyClass {
public:
operator bool() const { return false; }
operator T() const { return t; }
private:
T t;
};
您可以使用SFINAE 禁用以operator bool
当T
是类似bool
时
template <typename T = bool>
class MyClass {
public:
template <typename U = T, typename std::enable_if<!std::is_same<U, bool>::value, bool>::type = true>
operator bool() const { return false; }
operator T() const { return t; }
private:
T t;
};
另一种选择是专门针对bool
template <typename T = bool>
class MyClass {
public:
operator bool() const { return false; }
operator T() const { return t; }
private:
T t;
};
template <>
class MyClass<bool> {
public:
operator bool() const { return false; }
private:
bool t;
};
您可以使用 SFINAE:
#include <iostream>
#include <type_traits>
template <typename T = bool>
class MyClass {
public:
template<typename U = T,typename = std::enable_if_t<!std::is_same_v<U,bool>,void>>
operator bool() const { return false; }
operator T() const { return t; }
private:
T t = true;
};
int main() {
MyClass mc;
std::cout << static_cast<bool>(mc);
MyClass<int> mc2;
std::cout << static_cast<bool>(mc2);
}
相关文章:
- 为什么 C++ 11 在 ios 类中添加了运算符 bool
- 返回 bool 作为 CPP 中 bool 运算符 [] 中的值
- 当 Type = bool 时,运算符 bool() 与模板 Type() 运算符冲突
- 在C++中重载运算符时,为什么T*优先于bool
- 在类外部定义显式运算符 bool() 时出错
- 在使用C 中使用多个三元运算符时,BOOL和ENUM类型超载的功能没有区分
- Visual Studio无法在布尔运算的上下文中实例化强制转换运算符模板(T=bool)
- isSet() 或运算符 void*() 或显式操作程序 bool() 或其他东西
- 扩展模板化类以在对象实例上具有运算符 bool<bool>
- VS2012 std::函数运算符 bool 意外返回 true
- 运算符 |= 在 std::vector <bool>上
- 为什么显式运算符 bool 允许我转换为任何基元类型
- 在包含向量的<bool>类中重新定义运算符 []
- 重载到bool运算符的非成员转换
- 为什么当bool = true时补码运算符不起作用?
- 自定义实现具有位表示的bool向量-如何实现运算符[]
- diab 5.7编译器中的逻辑与运算符返回非bool类型
- C++ bool std::运算符 < 键映射错误 std::unordered_set<int,std::hash<int>>
- 为什么运算符 char*() 在布尔上下文中覆盖运算符 bool() 常量
- c++中的bool运算符