问题
I have a class where I use std::mem_fn
to choose between helper functions.
- 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
(but in case of m_funcContainerInt
the compiler rise compile error)
error C2664: 'void (int &) const' : cannot convert argument 1 from 'int' to 'int &'
- I feel that I have not formulate the title of my question in a best way, can you please help me to formulate technically more correct title?
Why the compiler can convert argument 'myStruct' to 'myStruct &' in std::function
My simplified code is
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 {}
EDITED I am compiling on Microsoft visual studio 2013
回答1:
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
will turn off (most?) language extensions, I believe including the one causing you a problem here.
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.
来源:https://stackoverflow.com/questions/33345509/why-the-mvs-compiler-can-convert-argument-mystruct-to-mystruct-and-did-no