pointer to member / strange construction

  • Thread starter Alexander Stippler
  • Start date
A

Alexander Stippler

Can someone explain the following construct to me:
What is not clear to me is what the argument to foo is.
A pointer to a member?

template <class U>
static char foo(void (U::*)(void));

regards,
alex
 
A

Alexander Stippler

What looks strange to me is the U::* part. No function name, only
a class qualifier? Could you please give more detail or tell me, where to
look up in the standard.
Yes, it's a pointer to a member function of U. The function
takes no arguments and returns nothing. You could use it
this way:

struct realU {
void bar();
};
...
char c = foo(&realU::bar);

(the compiler should be able to derive 'U == realU' here)

Victor

Alex
 
V

Victor Bazarov

Alexander Stippler said:
What looks strange to me is the U::* part. No function name, only
a class qualifier? Could you please give more detail or tell me, where to
look up in the standard.

Please don't top-post.

The declaration of a formal argument does not require a name.
If I were to declare a stand-alone variable, I'd give it a name:

void (MyClass::*ptrToMemOfMyClass)(); // name is required

if the same declaration (of a pointer to a member) would happen
to be part of a function declaration, you could drop the name:

void foo( void (MyClass::*)() ); // foo is a function
^^^^^^^^^^^^^^^^^^^

As to the asterisk, are you familiar with the syntax

"<type-id> (*)(<arg-list>)"?

Example:

void foo(int (*)(double, char));
^^^^^^^^^^^^^^^^^^^^^

? In the declaration above the argument 'foo' takes is
a pointer to a function that takes two arguments and returns
int. Now, the only difference with a member function is that
it is prefixed with the class name and the scope resolution
operator:

void foo(int (MyClass::*)(double, char));

which means that the pointer is NOT to a regular function, but
to a non-static member function of MyClass.

The formal argument name is optional when declaring a function,
so the next two declarations are equivalent:

int foo(double d, char c);
int foo(double, char);

The same with pointers to functions:

int foo(int (*myfuncptr)(double,char));
int foo(int (*)(double,char));

('myfuncptr' is the name of the formal argument).

Relevant sections of the Standard include 8.3.5, 8.3.1, 8.3.3
(and all they reference).

Victor
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,102
Messages
2,570,646
Members
47,247
Latest member
GabrieleL2

Latest Threads

Top