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

Viewed 120

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

You can use 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);
}
Related