C++最佳实践 - 函数类型别名 std::function<T> 或 T

C++ best practice - function type alias std::function<T> or T

本文关键字:function lt gt std 最佳 函数 别名 类型 C++      更新时间:2023-10-16

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

我应该如何定义FuncTypeaddFunction参数,以及如何将它们存储在向量中(在最佳情况下,无需复制可调用对象)?

我会亲自使用:

typedef std::function<void(int,int)> FuncType;

void foo(const FuncType &func) { ... }

编辑: 考虑到对这篇文章的评论,这不是最好的性能,因为它需要虚拟调度。