I have a class where I use std::mem_fn
to choose between helper functions.
&
in m_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 &'
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
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.