pointer to const member function typedef

2019-02-07 22:39发布

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.

2条回答
Luminary・发光体
2楼-- · 2019-02-07 22:51

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);
查看更多
成全新的幸福
3楼-- · 2019-02-07 23:05

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;
查看更多
登录 后发表回答