我想将某些函数的指针传递给模板类,以便以后使用。我想知道是否:
如果使这些函数内联,是否有可能(在速度方面)有所作为?
函数本身可能是另一个函数的换行器,例如下面的示例:

//inline ?
void func_wrapper_1(){
    func1(arg1);
}
//inline ?
void func_wrapper_2(){
    func2(arg2);
}
并且类模板类似于以下示例:
template<void(*f1)(), void(*f2)()>
class caller{
public:
    static void func(int v){
        if(v) {
            (*f1)();
        }else{
            (*f2)();
        }
    }
};
稍后在main函数中,它将像下面的示例一样使用:
    caller<func_wrapper_1,func_wrapper_2>::func(0);
    caller<func_wrapper_1,func_wrapper_2>::func(1);
我知道每件事都取决于编译器和编译选项,但是让我们假设编译器接受使这些函数内联。

最佳答案

编译器是否足够智能以内联给定情况尚待解决,但我认为通过重载function call operator创建可调用类型是可能的。
像这样:

template<typename Func1, typename Func2>
class caller{
public:
    static void func(int v){
        if(v) {
            // Func1() - creates an object of type Func1
            // that object is 'called' using the '()' operator
            Func1()();
        }else{
            Func2()();
        }
    }
};

struct CallableType1
{
    // overloading the function call operator makes objects of
    // this type callable
    void operator()() const { std::cout << "callable 1" << '\n'; }
};

struct CallableType2
{
    void operator()() const { std::cout << "callable 2" << '\n'; }
};

int main()
{
    caller<CallableType1, CallableType2> cc;

    cc.func(2);
}

关于c++ - 使用指向内联函数的指针与使用指向函数的指针,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/64073690/

10-11 22:38
查看更多