我编写了一段通用代码,它采用一组
std::function
作为参数。
void algorithm(function f, function g,...) {
...
f(...)
...
g(...)
....
}
函数f可以从一组具有相同签名的函数(f1,f2,...)中选择,g可以从一组具有相同签名的函数(g1,g2,..)中选择。有没有办法为多组参数自动编译
algorithm
多个?所以一个版本 algorithm_f1_g2
是用 f=f1
和 `g=g1 等编译的。
我已经尝试使用宏来实现此目的,但我没有走得太远。
PS:我真的希望在编译时实现这种通用行为以获得最大速度。
由于您可以将函数限制为某些预定义的集合(这意味着我们不必担心支持 lambda 或任意函子),因此您可以将
algorithm
实现为带有 函数指针参数的 函数模板 :
// Known signature for 'algorithm' parameters.
using AlgoFunction = void (*)(int);
// Set of predetermined parameter functions.
void f1(int){ /* ... */ }
void f2(int){ /* ... */ }
void ga(int){ /* ... */ }
void gb(int){ /* ... */ }
template <AlgoFunction f, AlgoFunction g>
void algorithm()
{
// ...
f(1);
// ...
g(2);
// ...
}
可以用作
algorithm<f1, ga>();
您甚至可以为特定的专业命名。例如,
constexpr auto algorithm_1a = algorithm<f1, ga>;
int main() {
algorithm_1a();
}