c++ - 在构造函数初始化器中使用 map 的初始化器列表

标签 c++ c++11 initializer-list pointer-to-member

尝试创建一个 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 草案,但之前的标准修订版也是如此):

[expr.unary.op/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” ([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/

相关文章:

c++ - 对象 vector 的初始化列表

c++ - 以编程方式在 IE 中设置页面缩放和文本大小

c++ - 为什么以及如何使用 C++ 允许使用动态值创建编译时数组

c++ - 从函数 : What is it compiled down to? 返回花括号初始化器列表

c++ - 可以在可变参数模板中推导出容器类型吗?

c++ - 在 shared_ptr 的复制构造函数中

c++ - 对非对象使用成员初始化列表不好吗?

十进制转十六进制的C++程序

c++ - 为什么函数accept()和recv()中地址长度参数是指针?

c++ - 什么特殊规则适用于一元 & 运算符?