Ant*_*yev 4 c++ templates c++11
当模板类型为 bool 时,我的模板运算符与 bool 运算符冲突(重载)。有什么办法解决这个问题吗?例如,我可以以某种方式“关闭”将operator T()T 分配给 bool 的时间吗?
template <typename T = bool>
class MyClass {
public:
operator bool() const { return false; }
operator T() const { return t; }
private:
T t;
};
Run Code Online (Sandbox Code Playgroud)
Nat*_*ica 10
您可以使用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;
};
Run Code Online (Sandbox Code Playgroud)
另一种选择是专注于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;
};
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
91 次 |
| 最近记录: |