加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

内置类型的基于C类型的调度

发布时间:2020-12-16 10:37:57 所属栏目:百科 来源:网络整理
导读:我需要一个调度程序功能,如下所示 templatetypename TT 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 dispatch
我需要一个调度程序功能,如下所示

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

你能告诉我怎么做到的吗?

附:
– 内置类型的解决方案只需要足够.
– 预处理和模板适用都是可以接受的.

解决方法

如果你有支持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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读