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


为什么不能推断出任何想法?我将感谢引用标准的答案。

编辑:

我发现了一个名为__closure的RAD Studio语言扩展,似乎正在解决此问题。1这是代码:

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

最佳答案

你不能用

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的类范围内也是如此。 —尾注]

关于c++ - 汽车无法推断?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/42286590/

10-11 23:01
查看更多