Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

My template operator is conflicting (overloading) with the bool operator when template type is bool. Any way of getting around this? For example, can I somehow "turn off" the operator T() when T is assigned to bool?

template <typename T = bool>
class MyClass {
public:
    operator bool() const { return false; }
    operator T() const { return t; }
private:
    T t;
};
like image 753
Anton Savelyev Avatar asked Dec 13 '22 08:12

Anton Savelyev


1 Answers

You can use SFINAE to disable to operator bool when T is a bool like

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;
};

Another option would be to specialize for bool like

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;
};
like image 75
NathanOliver Avatar answered Dec 16 '22 11:12

NathanOliver