2

In some C++ 98 code (meaning no, using std::function is not an option), I found the following construct:

class someClass
{
public:
    typedef void callback();

    void setCallback(callback c)
    {
        mCallback = c;
    }

    void callCallback()
    {
        if (mCallback)
            mCallback();
    }
private:
    callback *mCallback;
};

This confused me. I am used to passing callback functions as a function pointer, so I would expect setCallback to take (*callback)() as argument.

However, the above code seems to work, and compiles without any (related) warnings.

Could someone tell me what is happening here? Is my callback function implicitly passed as a function pointer? Is it a good idea to use this instead of function pointers?

The only thing I could find is that this construction results in "parameter-declaration-clause" ambiguity (C++ 98 8.3p7). Is this the only downside? Are there any benefits?

Bitbored
  • 473
  • 5
  • 16
  • a function type is adjusted to a pointer to function type in a parameter declaration – Piotr Skotnicki Sep 14 '15 at 09:27
  • 2
    When a function type is used as a function parameter type, it is adjusted to pointer-to-function type, so `setCallback` could equally have been declared as `void setCallback(callback * c)`. (Function types and array types are very similar in this and related regards.) – Kerrek SB Sep 14 '15 at 09:28
  • Is there any reference to this in the spec? As far as I know, this does not exists in C... – Bitbored Sep 14 '15 at 09:30
  • 2
    It's 8.3.5/5 in C++ (WD), and it's 6.7.6.3/8 in C11. – Kerrek SB Sep 14 '15 at 09:30
  • "After determining the type of each parameter, any parameter of type “array of T” or “function returning T” is adjusted to be “pointer to T” or “pointer to function returning T”, respectively". Thanks. – Bitbored Sep 14 '15 at 09:46
  • So, does anyone know if this has any advantages over using function pointers? – Bitbored Sep 14 '15 at 09:49
  • @Bitbored less typing when instantiating a function template, say `foo(bar)` instead of `foo(bar)` – Piotr Skotnicki Sep 14 '15 at 09:54

1 Answers1

0

Similarly to arrays, parameters of function type declare, in fact, a pointer to that type.

Quentin
  • 62,093
  • 7
  • 131
  • 191