pointer to const member function typedef

|▌冷眼眸甩不掉的悲伤 提交于 2019-11-30 10:58:44

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;
Billy Donahue

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);

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!