尝试创建一个 int 到成员函数指针的映射,并在构造函数初始值设定项中对其进行初始化。 像这样:
class X
{
using STATEFUNC = void(X::*)(int);
public:
X() : m{ { 1, &setState1 } } {}
void setState1(int x) { cout << "state1" << endl; }
void setState2(int x) { cout << "state2" << endl; }
std::map<int, STATEFUNC> m;
};
我会说这是正确的,但 Visual Studio 2017 说:
Error C2664 'std::map,std::allocator>>::map(std::initializer_list>)': cannot convert argument 1 from 'initializer list' to 'std::initializer_list>'
Error C2276 '&': illegal operation on bound member function expression
当您从成员函数中删除运算符的地址时,第一条错误消息保持不变,但第二条更改为:
Error C3867 'X::setState1': non-standard syntax; use '&' to create a pointer to member
如何在构造函数初始化列表中初始化 int 到成员函数指针的映射?
最佳答案
answer通过 max66是修复。至于为什么它是修复:原因是您的代码没有创建指向成员的指针。引用 n4659(最新的 C++17 草案,但之前的标准修订版也是如此):
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” ([conv.func]). Nor is &unqualified-id a pointer to member, even within the scope of the unqualified-id's class. — end note ]
X::setState1
是一个合格的 id,但 setState1
不是。
关于c++ - 在构造函数初始化器中使用 map 的初始化器列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45816776/