问题描述
我有一个类,其中我使用 std :: mem_fn
来选择辅助函数。
I have a class where I use std::mem_fn
to choose between helper functions.
- 为什么我的代码被编译和运行如果我在
m_funcContainer
减少了&
在代码&
中注释掉/ ** /
myStruct / *& /
- Why my code get compiled and run If I am missing
&
inm_funcContainer
deceleration ? In the code&
commented out with/**/
myStruct/*&*/
std :: map< std :: string,std :: function< void(const myClass *,myStruct / *& * /)> m_funcContainer
(但是 m_funcContainerInt
p>
(but in case of m_funcContainerInt
the compiler rise compile error)
- 我觉得我没有在最好的方法,你能帮我制定技术上更正确的标题吗?
我的简化代码是
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
EDITEDI am compiling on Microsoft visual studio 2013
推荐答案
您的问题是MSVC2013不是一个C ++编译器的默认设置。它编译与C ++密切相关的语言,但是具有扩展。
Your problem is that MSVC2013 is not a C++ compiler under its default settings. It is compiles a language closely related to C++, but with "extensions". You are being bitten by one of them.
/ Za
会关闭(大多数)语言扩充功能
/Za
will turn off (most?) language extensions, I believe including the one causing you a problem here.
我听说过有些MSVC(系统标题)附带的标题可能会有的问题, / Za
。并且,使用 / Za
关闭编译和测试的代码可能会在打开 / Za
时发生意外的行为更改。我会默认在新文件或项目中包含它,如果您有一个旧项目激活它并测试,它不会导致问题。
I have heard reports that some headers that ship with MSVC (system headers) can have problems with /Za
. And, code that was compiled and tested with /Za
off could have unexpected behavior changes with /Za
turned on. I would include it by default in new files or projects, and if you have an old project activate it and test that it doesn't cause problems.
这篇关于为什么MVS编译器可以将参数'myStruct'转换为'myStruct&'。并没有文件错误C2664:不能将'myStruct'转换为'myStruct&的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!