c++ deduce bool class template argument by constructor choice

132 views Asked by At

I am trying to deduce a bool template argument by the choice of the class constructor. A simple example:

template <typename A, bool Condition>
class Subrange {
    public:
    Subrange(A a) requires (not Condition); /* create Subrange<A, false> */
    Subrange(A a, int b) requires (Condition); /* create Subrange<A, true> */
};

Is this even possible or do one have to explicitly specify Condition on the constructor?
PS: Condition does not rely on A.

1

There are 1 answers

0
leslie.yao On

You can define user-defined deduction guide for class template argument deduction (CTAD) (since C++17) as:

template<typename A> Subrange(A a) -> Subrange<A, false>;
template<typename A> Subrange(A a, int b) -> Subrange<A, true>;

Then

Subrange s1(0);    // -> Subrange<int, false>
Subrange s2(0, 0); // -> Subrange<int, true>