Anton Lashkov Anton Lashkov - 3 months ago 15
C++ Question

C++, select function by template parameter

My question is how to call one of

process
function by runtime-known
id
without using map?

#include <iostream>
#include <map>

enum id
{
id_1,
id_2,
id_3
};

template <id id_>
void process();

template<>
void process<id_1>()
{
std::cout << "1" << std::endl;
}

template<>
void process<id_2>()
{
std::cout << "2" << std::endl;
}

template<>
void process<id_3>()
{
std::cout << "3" << std::endl;
}

std::map<id, void(*)()> mapping =
{
{id_1, process<id_1>},
{id_2, process<id_2>},
{id_3, process<id_3>}
};

int main()
{

for (int i = 0; i < 10; ++i)
{
mapping[static_cast<id>(rand()%3)]();
}

return 0;
}

Answer

map is an elegant solution.

If you don't want to use map, you have to 'map' the function calls yourself.

switch-case

void mapped_process(id id_) {
    switch (id_) {
    case id_1:
        process<id_1>();
        break;
    case id_2:
        process<id_2>();
        break;
    case id_3:
        process<id_3>();
        break;
    default:
        break;
    }
}

mapped_process(static_cast<id>(rand()%3);

map by index

Just as one of the comment mentioned, you can use array or vector to replace map with some constraint: the enums have unique values.

std::array<void(*)(), 3> procs = {process<id_1>, process<id_2>, process<id_3>};

procs[rand() % 3]();