Solomon Ucko
Solomon Ucko

Reputation: 6109

Define conversion operator only for some template specializations: expected a type / expected type-specifier

template<int a>
class A {};
operator A<0>::bool() {
    return true;
}

// Goal:
bool b1 = A<0>();   // Allow
//bool b2 = A<1>(); // Error

CLion gives the error "Expected a type" on the second A. GCC gives the error "expected type-specifier" on A<0>. This gives a similar error when typename is used instead of int. Why, and how can I only define a conversion for some template specializations?

Version info:

C++ 20, CLion 2019.1.4, CMake 3.14.3, GCC 8.3.0, Debian 8.3.0-6

Upvotes: 0

Views: 163

Answers (2)

pure cuteness
pure cuteness

Reputation: 1645

You might use SFINAE for this:

template<int a>
class A {
public:
    template<int B = a, class = std::enable_if_t<B == 0>>
    operator bool() const {
        return true;
    }
};

Upvotes: 1

Solomon Ucko
Solomon Ucko

Reputation: 6109

I think the solution is to move the operator keyword to after the double colon: A<0>:: operator bool(), and add template<> before the definition. The class should declare it as a normal operator method. Thanks to this link posted by Igor Tandetnik.

Upvotes: 0

Related Questions