简体   繁体   English

如何使用条件调用两个 C++ 模板函数之一

[英]How to call one of two C++ template functions with condition

There is a class with two member template functions: fun1(), fun2().有一个class,有两个成员模板函数:fun1()、fun2()。 I want to call one of the functions decided by a const bool class member: willCallFun1.我想调用由 const bool class 成员决定的函数之一:willCallFun1。 There is a solution like fun() in the code, but the if-else branch will check every times while fun() is called.代码中有类似 fun() 的解决方案,但是 if-else 分支会在每次调用 fun() 时检查。 I want avoid branch.我想避免分支。 Since when the Foo object is constructed, const bool willCallFun1 has been set, so which function of fun1 and fun2 will be used can already be determined.由于构造Foo object时,已经设置了const bool willCallFun1,所以已经可以确定fun1和fun2使用哪个function。

class Foo {
public:

  const bool willCallFun1;

  Foo(bool b) : willCallFun1{b}{
  }

  template<typename T>
  void fun1(T t) {
    std::cout << "fun1 "<< t << "\n";
  }

  template<typename T>
  void fun2(T t) {
    std::cout << "fun2 "<< t << "\n";
  }

  template<typename T>
  void fun(T t){
    if (willCallFun1) fun1<T>(t);
    else fun2<T>(t);
  }

};

int main() {
    Foo f1{true};
    f1.fun(123);
    f1.fun("hi");

    Foo f2{false};
    f2.fun(456);
    f2.fun("hello");
}

If fun1, fun2 are non-template functions, I can add a new member in the class, such as a function pointer or std::function to bind one of them at the constructor.如果 fun1、fun2 是非模板函数,我可以在 class 中添加一个新成员,例如 function 指针或 std::function 以在构造函数中绑定其中一个。 I can't find a way to do it when they are template functions.当它们是模板函数时,我找不到一种方法来做到这一点。 I would be very grateful if someone could answer.如果有人能回答我将不胜感激。

Since you can't make willCallFun1 into a template parameter and use if constexpr to decide which function to call, you could create an array of member function pointers and lookup the correct one using willCallFun1 as an index variable.由于您不能将willCallFun1为模板参数并使用if constexpr来决定调用哪个 function,因此您可以创建一个成员 function 指针数组并使用willCallFun1作为索引变量查找正确的指针。

template <typename T>
void fun(T t) {
    using fun_sig = void(Foo::*)(T);

    static constexpr fun_sig funs[] = {&Foo::fun2<T>, &Foo::fun1<T>};

    (this->*funs[willCallFun1])(t);
}

Demo演示

I'd test if this is actually faster than having a simple if though.我会测试这是否真的比简单的if更快。 I've done this before with disappointing results.我以前做过这个,但结果令人失望。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM