Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ type-based dispatch for builtin types

Tags:

c++

templates

I need a dispatcher function, something like below

template<typename T>
T dispatcher() {
    // if T is double
    return _func_double();
    // if T is int
    return _func_int();
    // if T is char*
    return _func_char_pointer();
}

and will be used like below

// some code that use above dispatcher
template<typename T1, typename T2, typename T3>
void do_multiple_thing(T1 *a1, T2 *a2, T2 *a3) {
    *a1 = dispatcher<T1>();
    *a2 = dispatcher<T2>();
    *a3 = dispatcher<T3>();
}

Could you tell me how to achieve that?

P.S.
- solution for builtin types only suffices.
- both preprocessing and template appoach is acceptable.

like image 796
qeatzy Avatar asked Sep 05 '25 03:09

qeatzy


1 Answers

If you have compiler with C++17 support this snippet of code should work:

template<typename T>
T dispatcher() {
    // if T is double
    if constexpr (std::is_same<T, double>::value)
        return _func_double();
    // if T is int
    if constexpr (std::is_same<T, int>::value)
        return _func_int();
    // if T is char*
    if constexpr (std::is_same<T, char*>::value)
        return _func_char_pointer();
}

Otherwise you will have to do template specialization, and make overload for each of parameters that you want

//only needed for static assert
template<typename T>
struct always_false : std::false_type {};


template<typename T>
T dispatcher() 
{ 
//to make sure that on type you didn't overload you will have exception
    throw std::exception("This type was not overloaded")
//static assert that will provide compile time error
    static_assert(always_false<T>::value , "You must specialize dispatcher for your type");
}
//or to get compile time error without static assert 
template<typename T>
T dispatcher() = delete; //the simplest solution

template<>
double dispatcher<double>() 
{
    return _func_double();
}
//... and so on for all other functions
like image 111
wdudzik Avatar answered Sep 07 '25 21:09

wdudzik