在C++中声明函数类型别名时,什么被认为是最佳或良好的实践(我知道这部分问题可能是主观的)?要么
using FuncType = void(int, int);
或者
using FuncType = std::function<void(int, int)>;
哪个更具优势?
当作为函数参数(传递为函数对象、lambda表达式、成员函数或全局函数)时,应该如何使用这些类型,例如:
void foo(FuncType&& func) { ... }
void foo(FuncType func) { ... }
void foo(std::function<FuncType> func) { ... }
编辑
我知道上面的例子并不都适用于 #1 和 #2,但这不是重点。我想知道哪个选项更好(以及为什么),如何在将其用作函数参数时传递此类型。
具体应用场景
由于问题似乎太广泛了(我完全理解),因此我将提供有关我的具体情况的更多细节。
我有一个类,其中包含我希望调用的函数向量(很可能是并行的,但我认为这并不重要)。在这个类中,我可以在运行时向向量中添加函数。
例如:
class
Container
{
public:
using FuncType = std::function<void(const SomeComplexDataType&, int, double)>;
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<FuncType> _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
的参数,以及如何将它们存储在向量中(最好的情况下,不复制可调用对象)?
std::function
会有显著的开销。 - llllllllll