c++ - auto 无法推断?

标签 c++ c++11 function-pointers auto member-pointers

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 标准中的相关文本:

Unary Operators

...

4 A pointer to member is only formed when an explicit & is used and its operand is a qualified-id not enclosed in parentheses. [ Note: that is, the expression &(qualified-id), where the qualified-id is enclosed in parentheses, does not form an expression of type “pointer to member.” Neither does qualified-id, because there is no implicit conversion from a qualified-id for a non-static member function to the type “pointer to member function” as there is from an lvalue of function type to the type “pointer to function” (4.3). Nor is &unqualified-id a pointer to member, even within the scope of the unqualified-id’s class. —end note ]

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

相关文章:

C++ 通过指针传递/访问矩阵

c++ - ioroutin.c :67:4: warning: implicit declaration of function ' ' is invalid in C99

c++ - 什么时候使用初始化列表构造函数?

c++ - 返回 C++ 函数最后一个参数的通用包装器

c++ - 检查哪些输出写入了标准输出

c++ - Istream 失败。什么是安全的使用方法!

c++ - *this 的 std::move 和稍后对类方法和字段的访问

c++ - 我如何强类型定义非原始类型?

C++ 可变参数模板基础

c++ - 有没有办法在没有 reinterpret_cast 的情况下保存多种类型的函数指针?