C++ 指向常量成员函数typedef的指针
我知道有可能创建一个指向成员函数的指针C++ 指向常量成员函数typedef的指针,c++,function,pointers,member,C++,Function,Pointers,Member,我知道有可能创建一个指向成员函数的指针 struct K { void func() {} }; typedef void FuncType(); typedef FuncType K::* MemFuncType; MemFuncType pF = &K::func; 有没有类似的方法来构造指向常量函数的指针?我尝试在不同的地方添加const,但没有成功。我已经玩了一些gcc,如果你做了一些模板推断,比如 template <typename Sig, typename Kla
struct K { void func() {} };
typedef void FuncType();
typedef FuncType K::* MemFuncType;
MemFuncType pF = &K::func;
有没有类似的方法来构造指向常量函数的指针?我尝试在不同的地方添加const,但没有成功。我已经玩了一些gcc,如果你做了一些模板推断,比如
template <typename Sig, typename Klass>
void deduce(Sig Klass::*);
模板
无效推断(Sig Klass::*);
它将Sig显示为一个函数签名,末尾加上const。如果在代码中这样做,它会抱怨不能在函数类型上使用限定符。似乎这应该是可能的,因为扣减是有效的。您想要这样:
typedef void (K::*MemFuncType)() const;
如果您仍希望将MemFuncType
建立在FuncType
的基础上,则需要更改FuncType
:
typedef void FuncType() const;
typedef FuncType K::* MemFuncType;
显示如何在没有typedef的情况下执行此操作的轻微改进。 在如下推导的上下文中,不能使用typedef
template <typename Class, typename Field>
Field extract_field(const Class& obj, Field (Class::*getter)() const)
{
return (obj.*getter)();
}
另一种更直接的方法(避免使用
和typedef
s)是:
#包括
类对象
{
国际组织;
公众:
int j_;
对象()
:对象(0,0)
{}
对象(inti,intj)
:i_(i),
j_uj(j)
{}
void printIplusJplusArgConst(int arg)const
{
是的,你是对的,它能工作!我以为我试过第二台,但猜不到,那是另一台机器,虽然可能是旧的编译器。明天必须再次检查。
class Foo {
public:
int get_int() const;
};
Foo obj;
int sz = extract_field(obj, &Foo::get_int);
#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;
}