Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

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);


In 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;


Yeah, typedefs solve the problem for fixed types. I guess you could use a macro to create a generic FUNC_PTR or something as well.


Macros 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?


There are a few other problems with multiple declarations aren't there? I though they were discouraged in c.


In C++, pointers to member functions are even more cumbersome than C function pointers.


  auto 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);


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.

And std::function introduce some performance overhead.


> 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.


Indeed, C++ is an excellent language, extremely writable; but readable, it isn't.


Agreed. I rarely use pmf's, so every time I do I have to look up the syntax again.


You could also do

    void foo(std::function<void(int)> callback);




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: