3 ms·
Whenever using C++11, I try to use std::function everywhere instead of function pointers, because it ends up being so, so much more readable. Taking the articl
by MereInterest 12y ago
Whenever using C++11, I try to use std::function everywhere instead of function pointers, because it ends up being so, so much more readable. Taking the article's last example, I rewrite it using std::function.
void (*signal(int, void (*fp)(int)))(int);
function<function<void(int)> (int, function<void(int)>) > signal;
It is more verbose, but easier to read, in my opinion. The return value of signal, function<void(int)>, is in one place, instead of being split into the beginning and end of the expression.
As an added bonus, it can also handle lambda functions or bound methods, which the function pointer version cannot.
- evincarofautumn 12y agostd::function has runtime overhead, though. Maybe you’d prefer a type alias with the same syntax as std::function? template<class F> struct func_ {}; template<class Result, class... Args> struct func_<Result(Args...)> { typedef Result(*type)(Args...); }; template<class F> using func = typename func_<F>::type; func<func<void(int)>(int, func<void(int)>)> signal;
- MereInterest 12y agoOoh, I hadn't thought of that. I will generally use a templated form if I care about the runtime overhead, or a std::function if I want to support multiple types of callables within the same container, and so I don't use raw function pointers very often.
- evincarofautumn 12y agoBy the way, I’m an idiot. template<class T> using ptr = T*; ptr<ptr<void(int)>(int, ptr<void(int)>)> signal; :)