2

Say I have a class that takes a boolean in its constructor and depends on the value of the boolean, if calls different functions.

class MyClass {
    MyClass(bool is_second)
    {
        common_code();
        if (!is_second)
            first_constructor();
        else
            second_constructor();
    }
};

I am new to C++17 and I am wondering if it is possible to write this logic using template programming and if constexpr. The api is something like this:

MyClass<> obj_calls_first_const;
MyClass<is_second_tag> obj_calls_second_const;
motam79
  • 3,542
  • 5
  • 34
  • 60

1 Answers1

8

Complying to your desired API:

struct is_second_tag { };

template <typename T = void>
struct MyClass
{
    MyClass()
    {
        if constexpr(std::is_same_v<T, is_second_tag>)
        {
            second_constructor();
        }
        else 
        {
            first_constructor();
        }
    }
};

live example on wandbox.org

Vittorio Romeo
  • 90,666
  • 33
  • 258
  • 416
  • Thanks. It works. If I have more than two branches (say is_third_tag, etc.). Can I use enums as the template variable? – motam79 Jun 27 '18 at 12:57