0
struct test 
{
  void f() {};
};
test t1;

using memfun_t = void (test::*)();
memfun_t mf = &test::f;


auto a1 = &test::f; // OK 
auto a2 = t1.*mf;  // error 
auto a3 = &(t1.*mf); // still no luck

Any ideas why this can't be deduced? I would appreciate answers referencing the Standard.

Edit :

I have found a RAD Studio language extension called __closure that appears to be addressing this issue.1 Here is the code :

class base {
public:
    void func(int x) {
    };
};

typedef void(base::*pBaseMember)(int);

class derived : public base {
public:
    void new_func(int i) {
    };
};

int main(int argc, char * argv[]) {
    derived derivedObject;
    void(__closure * derivedClosure)(int);

    // Get a pointer to the ‘new_func’ member.
    // Note the closure is associated with the
    // particular object, ‘derivedObject’.
    derivedClosure = derivedObject.new_func;

    derivedClosure(3); // Call ‘new_func’ through the closure.
    return 0;
}

http://docwiki.embarcadero.com/RADStudio/Seattle/en/Closure

4

1 回答 1

1

你不能使用

auto a2 = t1.*mf;  // error 

就像你不能使用:

auto a2 = t1.f;

t1.f不是一个有效的表达式。无法通过类的实例获得指向成员函数的指针。不像非成员函数那样使用时会衰减为函数指针,成员函数不会衰减为成员函数指针。

C++11 标准的相关文本:

一元运算符

...

4 指向成员的指针仅在使用显式&且其操作数是未括在括号中的限定 ID 时才形成。[注意:也就是说,&(qualified-id)括号qualified-id括起来的表达式不构成“指向成员的指针”类型的表达式。也没有qualified-id,因为没有从非静态成员函数的限定id到类型“指向成员函数”的隐式转换,因为从函数类型的左值到类型“指向函数”(4.3) . 即使在unqualified-id类的范围内,也不是 &unqualified-id指向成员的指针。——尾注]

于 2017-02-16T23:25:59.557 回答