当 Type = bool 时,运算符 bool() 与模板 Type() 运算符冲突

Operator bool() conflicting with template Type() operator when Type = bool

本文关键字:bool 运算符 Type 冲突      更新时间:2023-10-16

当模板类型为 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 boolT是类似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);
}