指向const成员函数typedef的指针

时间:2010-06-16 04:54:47

标签: c++ function pointers member

我知道可以分开创建一个指向成员函数的指针,如

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

是否有类似的方法来构造指向const函数的指针?我尝试在各个地方添加const但没有成功。我已经玩了一些gcc,如果你在

之类的东西上做模板演绎
template <typename Sig, typename Klass>
void deduce(Sig Klass::*);

它会将Sig作为函数签名显示,而const只是在最后添加。如果要在代码中执行此操作,则会抱怨您无法在函数类型上使用限定符。看起来它应该是可能的,因为演绎有效。

3 个答案:

答案 0 :(得分:33)

你想要这个:

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

如果您仍想MemFuncType FuncType,则需要更改FuncType

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

答案 1 :(得分:8)

稍微改进一下,显示如何在没有typedef的情况下执行此操作。 在如下所示的推断上下文中,您不能使用typedef。

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

使用const getter应用于某个类:

class Foo {
 public:
  int get_int() const;
};

Foo obj;
int sz = extract_field(obj, &Foo::get_int);

答案 2 :(得分:0)

另一种更直接的方法(避免使用usingtypedef)是这样的:

#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是指向Object的const方法指针。

相关问题