5 ms·
This is one of those cases where I prefer C++ template <typename Func> using function_ptr = add_pointer_t<Func>; and now declarations are a bit more sane:
by bstamour 10y ago
This is one of those cases where I prefer C++
template <typename Func> using function_ptr = add_pointer_t<Func>;
and now declarations are a bit more sane:
void foo(function_ptr<void (int)> callback);
- david-given 10y agoIn C, the easiest thing to do is to just use a typedef. You get to use the same syntax as for normal function calls with no trying to remember where that blasted extra * goes, and typically end up with cleaner code anyway. typedef void function_ptr_t(int i); function_ptr_t* ptr;
- bstamour 10y agoYeah, typedefs solve the problem for fixed types. I guess you could use a macro to create a generic FUNC_PTR or something as well.
- ramshorns 10y agoMacros are often a bad idea for defining types. If you do #define INT_PTR int* INT_PTR p, q; the code is actively misleading. Is there a better way to do it for function pointers?
- flukus 10y agoThere are a few other problems with multiple declarations aren't there? I though they were discouraged in c.
- Const-me 10y agoIn C++, pointers to member functions are even more cumbersome than C function pointers.
- bstamour 10y agoAgreed. I rarely use pmf's, so every time I do I have to look up the syntax again.
- kllrnohj 10y agoauto greet = std::mem_fn(&Foo::display_greeting); Looks pretty simple to me, much simpler than C function pointers. :) Pairs nicely with std::bind, too, like so: Foo foo; std::function<void(int)> setter = std::bind(&Foo::setValue, &foo, std::placeholders::_1); setter(42);
- Const-me 10y agoIf you need to keep that pointer in a collection, or in a class member, or pass as a function argument, “auto” won’t work. And std::function introduce some performance overhead.
- kllrnohj 10y ago> If you need to keep that pointer in a collection, or in a class member, or pass as a function argument, “auto” won’t work. Trivially solved with decltype, no need to remember anything. decltype(std::mem_fn(&Foo::Whatever)) Typedef it if you want. > And std::function introduce some performance overhead. It's the same performance as a virtual function call. Pretty much the same as a function pointer invoke.
- Koshkin 10y agoIndeed, C++ is an excellent language, extremely writable; but readable, it isn't.
- quinnftw 10y agoYou could also do void foo(std::function<void(int)> callback);