C ++ best practice is an alias of type of function std :: function <T> or T

What is considered best or good practice when declaring type aliases for function types in C ++ (I know that this part of the question is probably subjective)? Or

using FuncType = void(int, int); 

or

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

Are there any advantages of one over the other?

How to use these types as arguments to a function (when passed as a functor, lambda, member, or global function), for example

 void foo(FuncType&& func) { ... } void foo(FuncType func) { ... } void foo(std::function<FuncType> func) { ... } 

EDIT

I know that not all of my examples above apply to both # 1 and # 2, but this is not the case. I want to know which option (and why) is better, and how to pass this type when using it as an argument to a function.

Specific use case

Since it seems too wide (which I absolutely understand), I will tell you more about my specific case.

I have a class that contains a vector of functions that I want to name (most likely in parallel, but I don’t think it matters). In this class, I can add functions to the vector at runtime.

For instance:

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

How to define FuncType and parameter for addFunction and how can I store them in a vector (at best, without copying callers)?

+5
source share
1 answer

I would use:

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

and

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

edit: Not the best for performance, given the comment on this post, as it requires virtual submission.

0
source

Source: https://habr.com/ru/post/1275994/


All Articles