简体   繁体   中英

calling different function depending on type

I want to call different functions in a templated function depending on the type, like this:

template<typename T>
T func() {
    static_assert(std::is_same<T, int>::value || /* other allowed types */ , "Type not allowed");

    T ret {};
    // if T == int
    funcInt(&ret);
    // if T == /* other types */
    /* other functions */

}

Is such a thing possible?

I tried this:

std::function< int(*T)> query;
if (std::is_same<T, int>::value) {
    query = funcInt;
}

but this gives me an error:

error: 'T' does not refer to a value

is_same can be used in if statements just fine:

if (std::is_same<T, int>::value>) { /* stuff */ }
if (std::is_same<T, float>::value) { /* other stuff */ }

Altough this checks are in theory done at runtime, the compiler knows all values at compile time and will most likely remove any dead braches. The downside is that the entire code in func needs to be syntacticaly and sematically well formed, regardless of what T is. This may not be always feasible.

The proper template-ish way would be something like this:

template<typename>
struct helper;

template<>
struct helper<int> { static void do_work() { /* stuff */ } };

template<typename T>
T func()
{
    static_assert(std::is_same<T, int>::value || /* other allowed types */ , "Type not allowed");
    helper<T>::do_work();
}

This allows you to write common stuff in func and put the rest in specializations.

OTOH, if the signature of func is really this simple and there wouldn't be much code duplication, you might as well specialize func itself.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM