Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pointer to const member function typedef

I know it's possible to separate to create a pointer to member function like this

struct K { void func() {} }; typedef void FuncType(); typedef FuncType K::* MemFuncType; MemFuncType pF = &K::func; 

Is there similar way to construct a pointer to a const function? I've tried adding const in various places with no success. I've played around with gcc some and if you do template deduction on something like

template <typename Sig, typename Klass> void deduce(Sig Klass::*); 

It will show Sig with as a function signature with const just tacked on the end. If to do this in code it will complain that you can't have qualifiers on a function type. Seems like it should be possible somehow because the deduction works.

like image 597
oldcig Avatar asked Jun 16 '10 04:06

oldcig


People also ask

Can we use typedef for function pointer?

A typedef, or a function-type alias, helps to define pointers to executable code within memory. Simply put, a typedef can be used as a pointer that references a function.

How do you get a pointer to member function?

The pointer to member operators . * and ->* are used to bind a pointer to a member of a specific class object. Because the precedence of () (function call operator) is higher than . * and ->* , you must use parentheses to call the function pointed to by ptf .

Can we call member function using this pointer in constructor?

the constructor is the first function which get called. and we can access the this pointer via constructor for the first time. if we are able to get the this pointer before constructor call (may be via malloc which will not call constructor at all), we can call member function even before constructor call.

How do you pass this pointer to a function in C++?

Passing Pointers to Functions in C++ C++ allows you to pass a pointer to a function. To do so, simply declare the function parameter as a pointer type.


2 Answers

You want this:

typedef void (K::*MemFuncType)() const; 

If you want to still base MemFuncType on FuncType, you need to change FuncType:

typedef void FuncType() const; typedef FuncType K::* MemFuncType; 
like image 82
R Samuel Klatchko Avatar answered Sep 30 '22 16:09

R Samuel Klatchko


A slight refinement showing how to do it without a typedef. In a deduced context like the following, you can't use a typedef.

template <typename Class, typename Field> Field extract_field(const Class& obj, Field (Class::*getter)() const) {    return (obj.*getter)(); } 

applied to some class with a const getter:

class Foo {  public:   int get_int() const; };  Foo obj; int sz = extract_field(obj, &Foo::get_int); 
like image 38
Billy Donahue Avatar answered Sep 30 '22 18:09

Billy Donahue