gpt4 book ai didi

c++ - auto 无法推断?

转载 作者:行者123 更新时间:2023-11-28 05:17:38 26 4
gpt4 key购买 nike

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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com