指向 const 成员函数 typedef 的指针

问题描述 投票:0回答:3

我知道可以单独创建一个像这样的成员函数指针

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。如果在代码中执行此操作,它会抱怨您不能在函数类型上使用限定符。似乎应该有可能,因为推论有效。

c++ function pointers member const-member-function
3个回答
45
投票

你想要这个:

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

如果您想仍然以

MemFuncType
为基础
FuncType
,则需要更改
FuncType
:

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

11
投票

稍微改进一下,展示如何在没有 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);

3
投票

另一种更直接的方法(避免

using
typedef
)是这样的:

#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 方法指针。

© www.soinside.com 2019 - 2024. All rights reserved.