views:

151

answers:

2

This seems inconsistent. Why do we use &Example::func instead of Example::func? is there a use for Example::func or &exampleFunction? it doesnt seem like we can make a reference to a function so that rules out Example::func. and i cant think of a way to use &exampleFunction since exampleFunction already returns a pointer.

#include <iostream>
class Example {
public:
    void func() { std::cout <<"print me\n"; }
};
void exampleFunction() { std::cout << "print me too\n"; }
typedef void (Example::*ExampleFunc_t)(); 
typedef void (*ExampleFunction_t)();
int main()
{
    Example e;
    ExampleFunc_t     f  = &Example::func;
    ExampleFunction_t f2 = exampleFunction;
    (e.*f)();
    f2();
    return 0;
}
+1  A: 

The point is using Function Pointers. For a very rough example, suppose you have a class having several member variables by which you may need to sort of the elements of an array of that class type, like this:

struct CL {
    int x, y, z;
};

bool sort_by_x(const CL& obj1, const CL& obj2);
bool sort_by_y(const CL& obj1, const CL& obj2);
bool sort_by_z(const CL& obj1, const CL& obj2);

...

CL obj[100];
...
sort(obj, obj+100, sort_by_x);
...
sort(obj, obj+100, sort_by_y);
...
sort(obj, obj+100, sort_by_z);

Here std::sort is used to sort an array of CL objects. Look at the third parameter, it's name of a function. The std::sort function can take a function pointer in third parameter, and use that function as comparator to sort the array. It is upto us how to define sort_by_* functions so that std::sort works as expected.

Donotalo
+3  A: 

Because that's how the standard defines pointers to functions.

You actually always have to use the address operator & to get a pointer to a function, but for regular functions and static member function, an implicit conversion from function to pointer-to-function is defined in the standard.

This is not defined for a (non static) memberfunction because you can't obtain an lvalue to a non static memberfunction.

From the C++ standard:

4.3 Function-to-pointer conversion

  1. An lvalue of function type T can be converted to an rvalue of type “pointer to T .” The result is a pointer to the function.

with footnote 52:

This conversion never applies to non-static member functions because an lvalue that refers to a non-static member function cannot be obtained.

I think that they'd rather only allow &function, for consistency reasons, but that the implicit conversion is simply an artifact of the C heritage...

Pieter
dalle
yeah i think it's useful to have that implicit conversion for functions. because most often you want to pass a pointer anyway (you can't "pass a function", so it passes a pointer to it by implicit conversion). I guess the reason T::f does not suffice is because it would be ambiguous: If it would be
Johannes Schaub - litb
Johannes Schaub - litb