我在我的 c++
代码中经常使用函数指针,总是以符合这个简单规范示例的方式使用(例如,函数具有相同的 I/O,但所需的操作只是在运行时已知):
#include <iostream>
using namespace std;
int add(int first, int second){
return first + second;
}
int subtract(int first, int second){
return first - second;
}
int operation(int first, int second, int (*functocall)(int, int)){
return (*functocall)(first, second);
}
int main(){
int a, b;
int (*plus)(int, int) = add;
int (*minus)(int, int) = subtract;
a = operation(7, 5, plus);
b = operation(20, a, minus);
cout << "a = " << a << " and b = " << b << endl;
return 0;
}
我不久前开始使用它,只是因为我发现它更易于使用。
随着我更好地学习 c++,我发现自己在想:在这种情况下,从性能的角度来看,这种构造是否不好?如果是这样,为什么以及什么是更好的 c++11
-ish 替代品?
从性能的角度来看,我无法为这个简单的使用案例找到精确的指导方针(尽管有很多针对更复杂案例的指导方针)
编辑:
我隐含地假设 x86 硬件运行正常。
最佳答案
如果实在担心性能,可以考虑做编译时dispatch-templatize操作;这肯定适用于您的简单示例;不确定您的实际使用是否需要真正的运行时操作绑定(bind)(在这种情况下,此解决方案不起作用)。
template <typename Functor>
int operation(int first, int second, Functor f)
{
return f(first, second);
}
...
a = operation(7, 5, std::plus<int> /* since C++14, roll your own otherwise */);
b = operation(20, a, std::minus<int>);
通过函数指针调用的性能开销当然是不可忽略的,尤其是像add()和subtract()这样短小的函数;这就是为什么 C++ std::sort 比 C 的简单基本类型的 qsort 例程更胜一筹的原因。
关于c++ - 函数指针 : is the simple canonical use bad from a performance point of view? 如果是的话,c++11-ish 的替代方案是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26059916/