31

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.

oldcig
  • 313
  • 1
  • 3
  • 4

3 Answers3

45

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;
R Samuel Klatchko
  • 74,869
  • 16
  • 134
  • 187
  • Yes you are right it works! I thought I tried this second one, but guess not, that was another machine though maybe old compiler. Will have to check again tomorrow. – oldcig Jun 16 '10 at 05:09
11

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);
Silicomancer
  • 8,604
  • 10
  • 63
  • 130
Billy Donahue
  • 111
  • 1
  • 2
3

Another more direct way to do it (avoiding using and typedefs) is this:

#include <iostream>

class Object
{
    int i_;
public:
    int j_;
    Object()
        : Object(0,0)
    {}
    Object(int i, int j)
        : i_(i),
        j_(j)
    {}

    void printIplusJplusArgConst(int arg) const
    {
        std::cout << i_ + j_ + arg << '\n';
    }
};

int main(void)
{
    void (Object::*mpc)(int) const = &Object::printIplusJplusArgConst;

    Object o{1,2};
    (o.*mpc)(3);    // prints 6

    return 0;
}

mpc is a const method pointer to Object.

KeyC0de
  • 4,728
  • 8
  • 44
  • 68