首页 > 解决方案 > 内置类型的基于 C++ 类型的分派

问题描述

我需要一个调度程序功能,如下所示

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();
}

并将像下面一样使用

// 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>();
}

你能告诉我如何实现吗?

PS
- 内置类型的解决方案就足够了。
- 预处理和模板方法都是可以接受的。

标签: c++templates

解决方案


如果你有支持 C++17 的编译器,那么这段代码应该可以工作:

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();
}

否则,您将不得不进行模板专业化,并为您想要的每个参数进行重载

//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

推荐阅读