You are passing std::function<void (CMyObject&)>
to a function that expects std::function<void (CMyObject)>
(note the extra ampersand). These are distinct, unrelated types.
cannot convert from 'const _Ty2' to 'const std::function
Flaviu_
911
Reputation points
I have a bottleneck to my code:
Code:
void CSomeClass::SomeMethod(const std::string& method, const std::function<void (CMyObject)>& handler)
{
//
}
void CSomeClass::RegisterHandler(const web::http::method& Method, const MethodFn& Fn)
{
m_methodHandlerMap[Method] = Fn;
}
MethodHandlerMap CMyClass::GetHandlerMap() const
{
return m_methodHandlerMap;
}
using MethodFn = std::function<void(CMyObject&)>;
using MethodHandlerMap = std::unordered_map<std::string, MethodFn>;
MethodHandlerMap m_methodHandlerMap;
// code block
{
CSomeClass sc;
sc.RegisterHandler("AMethod", std::bind(&CSomeClassExtended::AMethod, this, std::placeholders::_1));
}
// code block
{
auto localMap = m_pMyClass->GetHandlerMap();
std::for_each(localMap.begin(), localMap.end(),
[this](const auto& handlePair)
{
m_object.SomeMethod(handlePair.first, handlePair.second); // ERROR !!! see below
});
}
and the error I got:
// error C2664: 'void CSomeClass::SomeMethod(const std::string &, const std::function<void (CMyObject)> &)': cannot convert argument 2 from 'const _Ty2' to 'const std::function<void (CMyObject)> &'
// note: Reason: cannot convert from 'const _Ty2' to 'const std::function<void (CMyObject)>'
the fact is that I write:
std::for_each(localMap.begin(), localMap.end(),
[this](const auto& handlePair)
{
m_object.SomeMethod(handlePair.first, nullptr); // is compiling ok
});
I didn't write the lambda correctly ? What I have done wrong ?
Accepted answer
-
Igor Tandetnik 1,106 Reputation points
2021-03-28T20:37:16.057+00:00
2 additional answers
Sort by: Most helpful
-
Viorel 112.7K Reputation points
2021-03-28T19:56:13.3+00:00 Check this:
void CSomeClass::SomeMethod( const std::string& method, const std::function<void( CMyObject& )>& handler )... or: void CSomeClass::SomeMethod( const std::string& method, const MethodFn & handler )...
-
Flaviu_ 911 Reputation points
2021-03-29T05:54:08.37+00:00 I cannot change
CSomeClass::SomeMethod
signature because is a part of a library. But I would take care of what you have told me.You told me both of you the source of the error, how can accept both answers as solution ? I will take on of you, but consider that both helped me to solve it ! Thanks a lot !