使用指向内联函数的指针与使用指向函数的指针

问题描述

我想将某些函数的指针传递给模板类,以供以后使用。我想知道是否:

如果我将这些函数内联,是否会对速度产生有益的影响?

函数本身可能是另一个函数的换行器,例如下面的示例:

//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创建 Callable Types 是可能的。

类似这样的东西:

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);
}