C++ 使用模板函数避免if-else语句

C++ 使用模板函数避免if-else语句,c++,templates,template-specialization,C++,Templates,Template Specialization,如果我有这样的代码: void function_1(...) { //do something } void function_2(...) { //do something } int function_3(...) { //do something } int main() { .... if (CONSTANT_1) function_1() else if (CONSTANT_2) function_2() else i

如果我有这样的代码:

void function_1(...)
{
    //do something
}


void function_2(...)
{
    //do something
}


int function_3(...)
{
    //do something
}

int main()
{
    ....
    if (CONSTANT_1) function_1()
    else if (CONSTANT_2) function_2()
    else if (CONSTANT_3) function_3()
    ....    
}
我希望避免使用if-else语句,并在main函数中执行类似操作:

int main()
{
    function<CONSTANT>();
}
intmain()
{
函数();
}

如何避免使用if-else语句并模拟此行为?

重载和标记分派。基本模板将该常量转换为唯一类型。然后简单重载解析将选择适当的重载。这都是假设常量是
constexpr
,而不是仅在运行时才知道的东西

void function(std::integral_constant<int, CONSTANT_1>)
{
    //do something
}


void function(std::integral_constant<int, CONSTANT_2>)
{
    //do something
}


int function(std::integral_constant<int, CONSTANT_3>)
{
    //do something
}

template<int constant>
auto function()
{
  return function(std::integral_constant<int, constant>{});
}

int main()
{
  function<CONSTANT_2>(); // calls the second overload
}
void函数(标准::积分常数)
{
//做点什么
}
空洞函数(标准:积分常数)
{
//做点什么
}
int函数(标准::积分常数)
{
//做点什么
}
模板
自动功能()
{
返回函数(std::积分常数{});
}
int main()
{
函数();//调用第二个重载
}

上述方法的好处是,当未找到重载时会发出编译时错误,而不是专门化模板函数时会出现链接错误。

通常,您可以专门化函数模板:

template<int N>
void function();

template<>
void function<1>()
{
    //do something
}

template<>
void function<2>()
{
    //do something
}

template<>
void function<3>()
{
    //do something
}
模板
空函数();
模板
空函数()
{
//做点什么
}
模板
空函数()
{
//做点什么
}
模板
空函数()
{
//做点什么
}

这是可行的,但也可能有更好的解决方案。

您必须使用模板吗?如果没有,您可以使用常量和函数指针的映射。然后调用从映射中得到的给定常数的函数。