专用模板调度独立于模板参数位置

Cof*_*ode 5 c++ templates c++14 c++17

我遇到了需要一个具有相同输出的模板函数的问题,只要它的模板参数是相同的,与位置无关.鉴于总有两个参数.

我有一个功能:

template<typename Lhs, typename Rhs>
int func();
Run Code Online (Sandbox Code Playgroud)

我想func<int, float>()func<float, int>()调用相同的代码.

我想过一个宏,我想避免使用它,但是当两种类型相同时我不需要重复代码.所以宏如:

#define DEF_TEMPL_IMPL(lhs, rhs, ret) \
template<>\
auto func<lhs, rhs>(){ return ret; }\
template<>\
auto func<rhs, lhs>(){ return func<lhs, rhs>(); }
Run Code Online (Sandbox Code Playgroud)

将无法编译因为DEF_TEMPL_IMPL(float, float, 3)会导致重新定义func<>

我认为SFINAE就是这里的答案,但我们无法想到解决方案.

我将继续思考这一点,但是在回答这个问题之前,堆栈溢出的一些优秀思想可能会比我能提出的更好或更优雅的解决方案.

那怎么能实现呢?

Tar*_*ama 9

您可以为每个类型对编写一个特化,然后func<Rhs,Lhs>()在调用它时将主模板委托给:

//This will get called if no specializations match
template<typename Lhs, typename Rhs>
int func() {
    //Check if there is a specialization for the flipped pair
    return func<Rhs, Lhs>();   
}

//This will get called for <int,float> and <float,int>
template <>
int func<int,float>() {
    return 42;   
}

//Ditto for <bool,float> and <float,bool>
template <>
int func<bool,float>() {
    return 0xbeef;   
}

//Specializations with the same arguments are also supported by this scheme
template <>
int func<bool,bool>() {
    return 12;   
}
Run Code Online (Sandbox Code Playgroud)

Live Demo