在C中为函数类型声明类型别名时,被认为是最佳或良好的做法(我知道这部分问题可能是主观的)?或
using FuncType = void(int, int);
要么
using FuncType = std::function;
一个人比另一个人有好处吗?
例如,我应该如何使用这些类型作为函数参数(当作为函子,lambda,成员或全局函数传递时)
void foo(FuncType&& func) { ... }
void foo(FuncType func) { ... }
void foo(std::function func) { ... }
编辑
我知道上面的所有例子都不适用于#1和#2,但这不是重点.我想知道哪个(以及为什么)选项更好,在将它用作函数参数时应该如何传递此类型.
具体用例
由于它看起来太宽泛(我完全理解),我将提供有关我的具体案例的更多细节.
我有一个类,它包含我想要调用的函数向量(最可能是并行的,但我认为这不重要).在这个类中,我可以在运行时向向量添加函数.
例如:
类
Container
{
public:
using FuncType = std::function;
inline void addFunction(FuncType func)
{
_funcs.push_back(func);
}
inline void call(const SomeComplexDataType& a, int b, double c)
{
for (auto& func : _funcs)
func(a, b, c);
}
private:
std::vector _funcs{};
};
struct HeavyFunctor
{
// contains some heavy objects
void operator()(const SomeComplexDataType& a, int b, double c)
{
/* Some heavy workload */
}
};
int main()
{
Container c;
c.addFunction([](const SomeComplexDataType& a, int b, double c) { /* do something lightweight */ });
c.addFunction(HeavyFunctor);
c.call(x, y, z);
return 0;
}
我应该如何定义FuncType和addFunction的参数以及如何将它们存储在向量中(在最好的情况下,不复制callables)?