Search code examples
c++enumsc++17constexprtag-dispatching

Using enum class values in constexpr branches


the code below prints val2 on both f() calls. What would be a proper way to execute specific branch in f() based on enum value ?

enum class E
{
    val1,
    val2
};

using val1_t = std::integral_constant<E, E::val1>;
using val2_t = std::integral_constant<E, E::val2>;
    

template <typename T>
void f(T t)
{
    if constexpr (std::is_same_v<T, val1_t>)
    {
        std::cerr << "val1\n";
    }
    else
    {
        std::cerr << "val2\n";
    }
}


int main()
{
    f(E::val1);
    f(E::val2);
}

Solution

  • If you move the enum into the template parameter, then you could use

    template <E val>
    void f()
    {
        if constexpr (val == E::val1)
        {
            std::cerr << "val1\n";
        }
        else
        {
            std::cerr << "val2\n";
        }
    }
    

    And you would use it like

    int main()
    {
        f<E::val1>();
        f<E::val2>();
    }