C++最佳实践 - 函数类型别名 std::function<T> 或 T
C++ best practice - function type alias std::function<T> or T
在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
参数,以及如何将它们存储在向量中(在最佳情况下,无需复制可调用对象)?
我会亲自使用:
typedef std::function<void(int,int)> FuncType;
和
void foo(const FuncType &func) { ... }
编辑: 考虑到对这篇文章的评论,这不是最好的性能,因为它需要虚拟调度。
相关文章:
- "error: no matching function for call to"构造函数错误
- 调用专用模板时出错"no matching function for call to [...]"
- 请解释这句话(cout<<1+int((a<b)^((b-a)&1) )<<endl
- 呼叫运营商<<临时
- 库函数需要一个 std::function<void(void)>,如何传入类函数?
- 如何防止clang格式在流运算符调用之间添加换行符<<
- Confusion: decltype vs std::function
- 为什么 std::function 可以作为 std::not2 的参数?
- 'max'匹配'std::function<const int &(const int &, const int &)>'无过载
- <<操作员在下面的行中工作
- 传递给std::function template的template参数究竟代表什么
- 将带有unique_ptr的可变 lambda 传递给 const&std::function
- 绑定派生类方法C++从实例范围之外的分隔 std::function 变量调用
- "no matching function for call to 'Vector::Vector'"错误
- 如何在向量中删除 std::function<void()>?
- 不断"Attempting to reference a deleted function"
- 将函数包装器转换为 std::function
- 类型擦除的std::function与虚拟函数调用的开销
- C++ std::function 对于类 exept 的所有实例都是空的(只有 Visual2019 编译器问题)
- 如果模板没有可变参数,则 Lambda 被推导出为 std::function