Search code examples
c++templatesoverloadingcopy-constructormove-constructor

Overloading based on bool template parameter


I have a template class with a single bool template parameter. I want to be able to implicitly convert from instantiations with the parameter equal to true, to those where it is equal to false.

I tried doing this (for the copy constructor), but the problem is that when I have Foo<true>, there are now two versions of the same constructor (with the same signature).

template <bool B>
class Foo
{
public:
    Foo(const Foo& other);
    Foo(const Foo<true>& other);
};

Not sure how to implement this? I also intend to have similar code for a move constructor and assignment.


Solution

  • You can apply SFINAE, to make Foo(const Foo<true>& other) only valid with Foo<false>.

    template <bool B>
    class Foo
    {
    public:
        Foo(const Foo& other);
        template <bool b = B, std::enable_if_t<!b>* = nullptr> // when b is false
        Foo(const Foo<true>& other);
    };