为什么 MVS 编译器可以将参数 'myStruct' 转换为 'myStruct &'。并且没有归档错误 C2664:无法将 'myStruct' 转换为 'myStruct &'

Why the MVS compiler can convert argument 'myStruct' to 'myStruct &'. And did not file error C2664: cannot convert 'myStruct' to 'myStruct &'

我有一个 class,我使用 std::mem_fn 在辅助函数之间进行选择。

  1. 为什么我的代码被编译并且 运行 如果我在 m_funcContainer 减速中缺少 &?在代码中 & 注释掉 /**/ myStruct/*&*/

std::map < std::string, std::function<void(const myClass*, myStruct/*&*/) >> m_funcContainer

(但如果m_funcContainerInt编译器会出现编译错误)

error C2664: 'void (int &) const' : cannot convert argument 1 from 'int' to 'int &'

  1. 我觉得我没有以最好的方式制定我的问题的标题,你能帮我制定技术上更正确的标题吗?

Why the compiler can convert argument 'myStruct' to 'myStruct &' in std::function

我的简化代码是

myClass.h

#include <memory>
#include <map>
#include <functional>

struct ExtraFlag
{
};

struct Flag
{
};

struct myStruct
{
    std::shared_ptr<ExtraFlag>         extraFlag;
    std::shared_ptr<Flag>              flag;

    explicit myStruct()
    {
    }
};

class myClass
{
private:
    std::map < std::string, std::function<void(const myClass*, myStruct/*&*/) >> m_funcContainer;
    std::map < std::string, std::function<void(const myClass*, int/*&*/) >> m_funcContainerInt;

private:
    void funcMyStruct(myStruct& arg1) const;
    void funcInt(int& arg1) const;
public:
    myClass();
};

myClass.cpp

#include "myClass.h"
myClass::myClass()
{
    m_funcContainer["func"] = std::mem_fn(&myClass::funcMyStruct);
    myStruct myStructInstance;
    m_funcContainer.at("func")(this, myStructInstance);

    int a;
    m_funcContainerInt["func"] = std::mem_fn(&myClass::funcInt);
    m_funcContainerInt.at("func")(this, a);
}
void myClass::funcMyStruct(myStruct& arg1) const
{}

void myClass::funcInt(int& arg1) const
{}

已编辑 我在 Microsoft visual studio 2013

上编译

你的问题是MSVC2013在其默认设置下不是C++编译器。它是编译一门与C++密切相关的语言,但具有"extensions"。你被其中一只咬了。

/Za 将关闭(大部分?)语言扩展,我相信包括给您带来问题的那个。

我听说一些 headers 随 MSVC(系统 headers)一起提供的 /Za 可能有问题。而且,在 /Za 关闭的情况下编译和测试的代码可能会在 /Za 打开时发生意外的行为变化。我会默认将它包含在新文件或项目中,如果您有一个旧项目,请激活它并测试它不会导致问题。