2

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);
}
2
  • 1
    std::is_same_v is comparing types, not values. E::val1 and E::val2 have the same type (E), which isn't the same type as std::integral_constant<...> Commented Sep 13, 2021 at 18:09
  • 1
    f(val1_t{}) would work. Commented Sep 13, 2021 at 18:12

1 Answer 1

10

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>();
}
Sign up to request clarification or add additional context in comments.

7 Comments

Thank you. So there is no way to somehow infer std::integral_constant-generated-type from passed enum value ? Maybe not with std::is_same_v, but somehow else ? I would still like to have something like f(E::val1) at call site.
@psb You could do something like this
@psb The issue with function parameters is they are never compile time constants. That means you can't use them where a compile time constant is required.
@psb That first example was a little to complicated. Here is a reduced version: coliru.stacked-crooked.com/a/c6ba1f71a2d9f76f
Yeah, I more or less understand that, but I've been thinking that since all enum values are known at compile time, there may be a way to deduce a type, based on enum value, from enum value at compile time.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.