What is considered to be best or good practice when declaring type aliases for function types in C++ (I know this part of the question is probably subjective)? Either
using FuncType = void(int, int);
or
using FuncType = std::function<void(int, int)>;
Are there benefits of one over the other?
How should I use these types as function arguments (when passing as 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 are applicable with both #1 and #2 but that is not the point. I want to know which (and why) option is better and how should I pass this type when using it as a function argument.
As it appears to be too broad (which I absolutely understand) I'm going to give more detail about my specific case.
I have a class that holds a vector of functions that I want to call (most likely parallel, but I don't think this matters). In this class I can add functions to the vector at runtime.
For example:
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 should I define FuncType
and the parameter for addFunction
and how can I store them in the vector (in a best case scenario, without copying the callables)?
I'd personnaly use:
typedef std::function<void(int,int)> FuncType;
and
void foo(const FuncType &func) { ... }
edit: Not the best for performance considering comment on this post as it requires virtual dispatch.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.