Lourens Dijkstra
Lourens Dijkstra

Reputation: 430

Called function instance must depend on parameter

I would like to make the function call depend on the parameter, that is, what version of the function is being called. I'm looking for a way to make the following code work, without making enum_value v a template argument. The goal is that if v==enum_value::A, the first instance is called. If v==enum_value::B the second instance must be called.

enum class enum_value { A, B, C };

auto foo(enum_value v) -> std::enable_if_t<v==enum_value::A>
{}

auto foo(enum_value v) -> std::enable_if_t<v==enum_value::B>
{}

Feel free to ask if I need to elaborate.

Upvotes: 0

Views: 38

Answers (1)

max66
max66

Reputation: 66210

I'm looking for a way to make the following code work, without making enum_value v a template argument

I don't think it's possible what do you want.

As pointed by Quentin, if the enum value is a function argument, it is known (potentially) only run-time. But the compiler have to select the function compile-time.

You can think that make foo() constexpr, passing a constexpr value as arguments, permit a compile time selection of the right function. But this doesn't works because a constexpr function can be executed compile-time, but can also be executed run-time. So the compiler give error because must consider the run-time case.

The best I can imagine (non a great solution, I know) is pass through a select function; something as

enum class enum_value { A, B, C };

void foo_A ()
 { }

void foo_B ()
 { }

// ....

void select_foo (enum_value v)
 {
   switch (v)
    {
      case A: foo_A(); break;
      case B: foo_B(); break;
      // ...
      default: break;             
    }
 }

Upvotes: 1

Related Questions