使用模板进行条件函数调用

时间:2016-06-23 01:23:30

标签: c++ c++11 template-meta-programming

是否有办法使用c ++模板(编译时代码生成)有条件地调用函数,其中基于参数的类型,每个变体的逻辑将是不同的

例如

(不是可编译的代码),

template <true, typename Var1, typename Var2, typename Var3>
int func(Var1 v1, Var2 v2, Var3 v3) {//logic type1}

template <false, typename Var1, typename Var2, typename Var3>
int func(Var1 v1, Var2 v2, Var3 v3) {//logic type2}

template <typename Var1, typename Var2, typename Var3>
int foo(Var1 v1, Var2 v2, Var3 v3)
{
    func<static_condition>(v1, v2, v3);
}

当用一些参数调用foo时,它将静态地评估它应该调用func的boolean标志。在这两种变体中执行的逻辑将导致编译错误,因此必须为每个操作分割它。

我正在搜索一些例子并发现_If _Then _Else模式使用模板元编程,但我不清楚如何在我的场景中使用它。

2 个答案:

答案 0 :(得分:10)

没有比这更容易了。

template <typename Var1, typename Var2, typename Var3>
int func(Var1 v1, Var2 v2, Var3 v3, std::true_type) {//logic type1}

template <typename Var1, typename Var2, typename Var3>
int func(Var1 v1, Var2 v2, Var3 v3, std::false_type) {//logic type2}

template <typename Var1, typename Var2, typename Var3>
int foo(Var1 v1, Var2 v2, Var3 v3)
{
    func(v1, v2, v3, std::integral_constant<bool, static_condition>());
}

答案 1 :(得分:3)

您可以使用enable_if有条件地关闭一个功能或另一个功能:

template <bool cond, typename Var1, typename Var2, typename Var3>
typename std::enable_if<cond, int>::type
func(Var1 v1, Var2 v2, Var3 v3) {//logic type1}

template <bool cond, typename Var1, typename Var2, typename Var3>
typename std::enable_if<not cond, int>::type
func(Var1 v1, Var2 v2, Var3 v3) {//logic type2}

template <typename Var1, typename Var2, typename Var3>
int foo(Var1 v1, Var2 v2, Var3 v3) {
    func<static_condition>(v1, v2, v3);
}