C++ overloaded method pointer [duplicate] - c++

This question already has answers here:
How do I specify a pointer to an overloaded function?
(6 answers)
Closed 7 years ago.
How do I get a method pointer to a particular overload of a method:
struct A {
void f();
void f(int);
void g();
};
I know that
&A::g
is a pointer to g. But how do I get a pointer to f or f(int)?

(void (A::*)()) &A::f
(void (A::*)(int)) &A::f
function pointers and member function pointers have this feature - the overload can be resolved by to what the result was assigned or cast.
If the functions are static, then you should treat them as ordinary functions:
(void (*)()) &A::f;
(void (*)(int)) &A::f;
or even
(void (*)()) A::f;
(void (*)(int)) A::f;

You just have to cast the result of &A::f in order to remove the ambiguity :
static_cast<void (A::*)()>(&A::f); // pointer to parameterless f
static_cast<void (A::*)(int)>(&A::f); // pointer to f which takes an int

Thanks to Stefan Pabst for the following idea, which he presented in a five minute lightning talk at ACCU 2015. I extended it with tag types to allow for resolving overloads by their cv qualifier and/or reference qualifier, and a C++17 variable template to avoid having to type the extra pair of parentheses which is otherwise required.
This solution works on the same principle as the cast-based answers, but you avoid having to restate either the return type of the function or, in the case of member functions, the name of the class which the function is a member of, as the compiler is able to deduce these things.
bool free_func(int, int) { return 42; }
char free_func(int, float) { return true; }
struct foo {
void mem_func(int) {}
void mem_func(int) const {}
void mem_func(long double) const {}
};
int main() {
auto f1 = underload<int, float>(free_func);
auto f2 = underload<long double>(&foo::mem_func);
auto f3 = underload<cv_none, int>(&foo::mem_func);
auto f4 = underload<cv_const, int>(&foo::mem_func);
}
The code implementing the underload template is here.

Related

C++ and pointer to function of class [duplicate]

This question already has answers here:
How can I pass a member function where a free function is expected?
(9 answers)
Closed 2 months ago.
If I have two classes like this :
class A
{
public:
int *(*fun)( const int &t );
A( int *( *f )( const int &t ) ) : fun( f ) {}
};
class B
{
private:
float r;
int *f(const int &t)
{
return new int( int( r ) + t );
}
A a;
B() : a( A( f ) ) {}
};
This results in compiler error.
I want to assign f to a's function pointer.
The thing is that A can be used by many classes not just B so I can't simply define fun as B::*fun.
None of the posts I've found on the internet and here on stackoverflow address the issue of using the function pointers with many classes each having its own member function but the same prototype.
So what to do?
this result in compiler error
Because f is a A's non-static member function returning int*, that accepts single const reference to int. That means, that its type is not:
int* (*)(const int &);
but:
int* (A::*)(const int&);
Also, your code signalizes very bad design - I think you need simple virtual function. But if you want to keep writing things this way, you may want to read: ISOCPP: Pointers to members.
Remember, that non-static member functions of type C always accepts additional implicit argument of type C* (or const C*, if function is declared with const qualifier), that points to instance of C this function was called on.
Your code looks confusing and, personally, I believe that C function pointers look ugly on C++'s OO implementation. So I would advise you to use the std::function. It only has been available since C++11. If you cannot use it, try looking on Boost's Implementation.
I can give you an example of how to use the std::function:
bool MyFunction(int i)
{
return i > 0;
}
std::function<bool(int)> funcPointer = MyFunction;
Using this you will drastically improve your code reliability. As of your problem, specifically:
class A
{
public:
std::function<int*(const int&)> fun;
A(std::function<int*(const int&)> f) : fun(f) {}
};
class B
{
private:
float r;
int *f(const int &t)
{
return new int(int(r) + t);
}
A *a;
B()
{
std::function<int*(const int&)> tempFun = std::bind(&B::f, this, _1);
a = new A(tempFun);
}
};
You have to add the following namespace:
using namespace std::placeholders;
So what to do
Not much. Other than templating A on the type of objects for which it will hold a pointer to a member function taking a reference to a const int and returning a pointer to int.
What you're trying to do is to mix a pointer to a free function with a pointer to member function. Whilst it sounds like they're both function pointers they're different enough to not be able to pass through the same type definition.

What's the function signature of a member function?

I'm having trouble understanding function signatures and pointers.
struct myStruct
{
static void staticFunc(){};
void nonstaticFunc(){};
};
int main()
{
void (*p)(); // Pointer to function with signature void();
p = &myStruct::staticFunc; // Works fine
p = &myStruct::nonstaticFunc; // Type mismatch
}
My compiler says that the type of myStruct::nonstaticFunc() is void (myStruct::*)(), but isn't that the type of a pointer pointing to it?
I'm asking because when you create an std::function object you pass the function signature of the function you want it to point to, like:
std::function<void()> funcPtr; // Pointer to function with signature void()
not
std::function<void(*)()> funcPtr;
If I had to guess based on the pattern of void() I would say:
void myStruct::();
or
void (myStruct::)();
But this isn't right. I don't see why I should add an asterisk just because it's nonstatic as opposed to static. In other words, pointer void(* )() points to function with signature void(), and pointer void(myStruct::*)() points to function with signature what?
To me there seems to be a basic misunderstanding of what a member pointer is. For example if you have:
struct P2d {
double x, y;
};
the member pointer double P2d::*mp = &P2d::x; cannot point to the x coordinate of a specific P2d instance, it is instead a "pointer" to the name x: to get the double you will need to provide the P2d instance you're looking for... for example:
P2d p{10, 20};
printf("%.18g\n", p.*mp); // prints 10
The same applies to member functions... for example:
struct P2d {
double x, y;
double len() const {
return sqrt(x*x + y*y);
}
};
double (P2d::*f)() const = &P2d::len;
where f is not a pointer to a member function of a specific instance and it needs a this to be called with
printf("%.18g\n", (p.*f)());
f in other words is simply a "selector" of which of the const member functions of class P2d accepting no parameters and returning a double you are interested in. In this specific case (since there is only one member function compatible) such a selector could be stored using zero bits (the only possible value you can set that pointer to is &P2d::len).
Please don't feel ashamed for not understanding member pointers at first. They're indeed sort of "strange" and not many C++ programmers understand them.
To be honest they're also not really that useful: what is needed most often is instead a pointer to a method of a specific instance.
C++11 provides that with std::function wrapper and lambdas:
std::function<double()> g = [&](){ return p.len(); };
printf("%.18g\n", g()); // calls .len() on instance p
std::function<void()> funcPtr = std::bind(&myStruct::nonstaticFunc, obj);
Is how you store a member function in std::function. The member function must be called on a valid object.
If you want to delay the passing of an object until later, you can accomplish it like this:
#include <functional>
#include <iostream>
struct A {
void foo() { std::cout << "A::foo\n"; }
};
int main() {
using namespace std::placeholders;
std::function<void(A&)> f = std::bind(&A::foo, _1);
A a;
f(a);
return 0;
}
std::bind will take care of the details for you. std::function still must have the signature of a regular function as it's type parameter. But it can mask a member, if the object is made to appear as a parameter to the function.
Addenum:
For assigning into std::function, you don't even need std::bind for late binding of the object, so long as the prototype is correct:
std::function<void(A&)> f = &A::foo;
p = &myStruct::staticFunc; // Works fine
p = &myStruct::nonstaticFunc; // Type mismatch
Reason : A function-to-pointer conversion never applies to non-static member functions because an lvalue that refers to a non-static member function
cannot be obtained.
pointer void(* )() points to function with signature void(), and pointer void(myStruct::*)() points to function with signature what?
myStruct:: is to make sure that the non-static member function of struct myStruct is called (not of other structs, as shown below) :
struct myStruct
{
static void staticFunc(){};
void nonstaticFunc(){};
};
struct myStruct2
{
static void staticFunc(){};
void nonstaticFunc(){};
};
int main()
{
void (*p)(); // Pointer to function with signature void();
void (myStruct::*f)();
p = &myStruct::staticFunc; // Works fine
p = &myStruct2::staticFunc; // Works fine
f = &myStruct::nonstaticFunc; // Works fine
//f = &myStruct2::nonstaticFunc; // Error. Cannot convert 'void (myStruct2::*)()' to 'void (myStruct::*)()' in assignment
return 0;
}
When you use a pointer, std::function or std::bind to refer to a non-static member function (namely, "method" of class Foo), the first param must be a concrete object of class Foo, because non-static method must be called by a concrete object, not by Class.
More details: std::function and
std::bind.
The answer is in the doc.
Pointer to member declarator: the declaration S C::* D; declares D as
a pointer to non-static member of C of type determined by
decl-specifier-seq S.
struct C
{
void f(int n) { std::cout << n << '\n'; }
};
int main()
{
void (C::* p)(int) = &C::f; // pointer to member function f of class C
C c;
(c.*p)(1); // prints 1
C* cp = &c;
(cp->*p)(2); // prints 2
}
There are no function with signature void (). There are void (*)() for a function or void (foo::*)() for a method of foo. The asterisk is mandatory because it's a pointer to x. std::function has nothing to do with that.
Note: Your confusion is that void() is that same signature that void (*)(). Or even int() <=> int (*)(). Maybe you think that you can write int (foo::*) to have a method pointer. But this is a data member pointer because the parenthesis are optional, int (foo::*) <=> int foo::*.
To avoid such obscure syntax you need to write your pointer to function/member with the return type, the asterisk and his parameters.

assign a member function to a function pointer [duplicate]

This question already has answers here:
How can I pass a member function where a free function is expected?
(9 answers)
Closed 2 months ago.
If I have two classes like this :
class A
{
public:
int *(*fun)( const int &t );
A( int *( *f )( const int &t ) ) : fun( f ) {}
};
class B
{
private:
float r;
int *f(const int &t)
{
return new int( int( r ) + t );
}
A a;
B() : a( A( f ) ) {}
};
This results in compiler error.
I want to assign f to a's function pointer.
The thing is that A can be used by many classes not just B so I can't simply define fun as B::*fun.
None of the posts I've found on the internet and here on stackoverflow address the issue of using the function pointers with many classes each having its own member function but the same prototype.
So what to do?
this result in compiler error
Because f is a A's non-static member function returning int*, that accepts single const reference to int. That means, that its type is not:
int* (*)(const int &);
but:
int* (A::*)(const int&);
Also, your code signalizes very bad design - I think you need simple virtual function. But if you want to keep writing things this way, you may want to read: ISOCPP: Pointers to members.
Remember, that non-static member functions of type C always accepts additional implicit argument of type C* (or const C*, if function is declared with const qualifier), that points to instance of C this function was called on.
Your code looks confusing and, personally, I believe that C function pointers look ugly on C++'s OO implementation. So I would advise you to use the std::function. It only has been available since C++11. If you cannot use it, try looking on Boost's Implementation.
I can give you an example of how to use the std::function:
bool MyFunction(int i)
{
return i > 0;
}
std::function<bool(int)> funcPointer = MyFunction;
Using this you will drastically improve your code reliability. As of your problem, specifically:
class A
{
public:
std::function<int*(const int&)> fun;
A(std::function<int*(const int&)> f) : fun(f) {}
};
class B
{
private:
float r;
int *f(const int &t)
{
return new int(int(r) + t);
}
A *a;
B()
{
std::function<int*(const int&)> tempFun = std::bind(&B::f, this, _1);
a = new A(tempFun);
}
};
You have to add the following namespace:
using namespace std::placeholders;
So what to do
Not much. Other than templating A on the type of objects for which it will hold a pointer to a member function taking a reference to a const int and returning a pointer to int.
What you're trying to do is to mix a pointer to a free function with a pointer to member function. Whilst it sounds like they're both function pointers they're different enough to not be able to pass through the same type definition.

How create a function pointer to point a member function? [duplicate]

This question already has answers here:
function pointer to a class member
(2 answers)
Closed 9 years ago.
Code:
struct A
{
void* f(void *)
{
}
};
int main()
{
void * (*fp)(void *);
fp = &A::f;
}
Compile:
|12|error: cannot convert 'void* (A::*)(void*)' to 'void* (*)(void*)' in assignment|
I have tried many ways, but all failed... How to do that?
For a regular member pointer, you'll need to declare the type it's a member of on the pointer type;
int main()
{
void * (A::*fp)(void *);
fp = &A::f;
}
Don't use function pointers use std::mem_fn
auto func = std::mem_fn(&A::f);
If you really want to use function pointers(you don't) you have to do this.
void * (A::*func)(void*);
func = &A::f;
IMO this is uglier, harder to read and less maintainable
You can also use std::function like this.
A a;
std::function<void*(const A &, void*)> f_add_display = &Foo::print_add;
but mem_fn is better suited for the job since you have a memfunction
std::function<void *( A&, void *)> fp = &A::f;

Non-pointer typedef of member functions not allowed?

After getting an answer to this question I discovered there are two valid ways to typedef a function pointer.
typedef void (Function) ();
typedef void (*PFunction) ();
void foo () {}
Function * p = foo;
PFunction q = foo;
I now prefer Function * p to PFunction q but apparently this doesn't work for pointer-to-member functions. Consider this contrived example.
#include <iostream>
struct Base {
typedef void (Base :: *Callback) ();
//^^^ remove this '*' and put it below (i.e. *cb)
Callback cb;
void go () {
(this->*cb) ();
}
virtual void x () = 0;
Base () {
cb = &Base::x;
}
};
struct D1 : public Base {
void x () {
std :: cout << "D1\n";
}
};
struct D2 : public Base {
void x () {
std :: cout << "D2\n";
}
};
int main () {
D1 d1;
D2 d2;
d1 .go ();
d2 .go ();
}
But if I change it to the new preferred style: typedef void (Base :: Callback) () and Callback * cb, I get a compiler error at the point of typedef
extra qualification 'Base::' on member 'Callback'
Demo for error.
Why is this not allowed? Is it simply an oversight or would it cause problems?
For non-member functions, a type such as typedef void(Function)() has several uses, but for member functions the only application is to declare a variable which holds a function pointer. Hence, other than a stylistic preference, there's no strict need to allow this syntax and it has been omitted from the standard.
Background
The :: is a scope resolution operator, and the syntax X::Y is reserved for static member access if X is a class type. So X::*Z was another syntax invented to define pointer-to-member.
Forget member-function for a while, just think about member-data, and see this code:
struct X
{
int a;
};
int X::*pa = &X::a; //pointer-to-member
X x = {100}; //a = 100
cout << (x.*pa) << endl;
It defines a pointer-to-member-data, and the cout uses it to print the value of a of object x, and it prints:
100
Demo : http://www.ideone.com/De2H1
Now think, if X::pa (as opposed to X::*pa) were allowed to do that, then you've written the above as:
int X::pa = X::a; //not &X::a
Seeing this syntax, how would you tell if X::a is a static member or non-static member? That is one reason why the Standard came up with pointer-to-member syntax, and uniformly applies it to non-static member-data as well as non-static member-function.
In fact, you cannot write X::a, you've to write &X::a. The syntax X::a would result in compilation error (see this).
Now extend this argument of member-data to member-function. Suppose you've a typedef defined as:
typedef void fun();
then what do you think the following code does?
struct X
{
fun a;
};
Well, it defines member a of type fun (which is function taking no argument, and returning void), and is equivalent to this:
struct X
{
void a();
};
Surprised? Read on.
struct X
{
fun a; //equivalent to this: void a();
};
void X::a() //yes, you can do this!
{
cout << "haha" << endl;
}
We can use exactly the same syntax to refer to a which is now a member-function:
X x;
x.a(); //normal function call
void (X::*pa)() = &X::a; //pointer-to-member
(x.*pa)(); //using pointer-to-member
The similarity is the synatax on the right hand side : &X::a. Whether a refers to a member-function or member-data, the syntax is same.
Demo : http://www.ideone.com/Y80Mf
Conclusion:
As we know that we cannot write X::a on the RHS, no matter if a is a member-data or member-function. The only syntax which is allowed is &X::f which makes it necessary that the target type (on LHS) must be pointer as well, which in turn makes the syntax void (X::*pa)() absolutely necessary and fundamental, as it fits in with other syntax in the language.
To be precise the two typedef's in the case of the non-member pointers are not the same:
typedef void function();
typedef void (*fptr)();
The first defines function as a function taking no arguments and returning void, while the second defines ftpr as a pointer to function taking no arguments and returning void. The confusion probably arises as the function type will be implicitly converted to a pointer type in many contexts. But not all:
function f; // declares void f();
struct test {
function f; // declares void test::f()
};
void g( function f ); // declares g( void (*f)() ): function decays to pointer to function in declaration
g( f ); // calls g( &f ): function decays to pointer to function
void f() {} // definition of f
// function h = f; // error: cannot assign functions
function *h = f; // f decays to &f
Let's skip the "function" part for a second. In C++, we have the int, the int* and the int Foo::* types. That's a regular integer, pointer to integer, and a pointer to an integer member. There is no fourth type "integer member".
Exactly the same applies to functions: there's just no type "member function", even though there are function types, function pointer types, and member function pointer types.