[英]Inserting <string, function pointer> into map
I'm having trouble with inserting some value_pairs into a map. 我在将一些value_pairs插入地图时遇到麻烦。 Here's the basic idea.
这是基本思想。
// private
typedef Foo* (*Bar)( const std::string &x, int y );
typedef std::map<std::string, Bar> myMap;
template<class T>
Foo* DoThing( const std::string &x, int y ) {
return new T( x, y );
}
myMap m_map;
// some map insertion code
m_map.insert( myMap::value_type( "blah", &DoThing<SomeType> ));
m_map.insert( myMap::value_type( "blech", &DoThing<OtherType> ));
This would give a compiler error saying no matching function call to std::pair<const std::basic_string<char, std::char_traits<char>, std::allocator<char> >, Foo* (*)(const std::string&, int)>::pair(const char [5], <unresolved overloaded function type>)
Not sure what I'm doing wrong syntactically, or why I'm getting the unresolved overloaded function type
. 这将导致编译器错误,表明
no matching function call to std::pair<const std::basic_string<char, std::char_traits<char>, std::allocator<char> >, Foo* (*)(const std::string&, int)>::pair(const char [5], <unresolved overloaded function type>)
不知道我在语法上做错了什么,或者不确定为什么我得到了unresolved overloaded function type
。 My best guess is that it doesn't know that DoThing
returns a Foo*
. 我最好的猜测是,它不知道
DoThing
返回Foo*
。
Any help appreciated, thanks. 任何帮助表示赞赏,谢谢。
Comment converted to answer: 评论转换为答案:
Just to be sure, DoThing<T>
is a global function and not a member of any class, right? 可以肯定的是,
DoThing<T>
是全局函数,而不是任何类的成员,对吗? If it's inside a class, it needs to be a static member function. 如果在类内部,则它必须是静态成员函数。
Also, if you take the address of a member function, some compilers insist on qualifying it with the class name, eg &MyClass::DoThing<T>
. 另外,如果使用成员函数的地址,则某些编译器会坚持使用类名来限定它,例如
&MyClass::DoThing<T>
。 Again, if it is a static member function, you get an ordinary function pointer. 同样,如果它是静态成员函数,则将获得一个普通的函数指针。 If a non-static member function, you get a pointer-to-member and the
this
pointer must be supplied at the call site. 如果是非静态成员函数,则会获得指向成员的指针,并且必须在调用站点处提供
this
指针。
您在第二个&之前忘记了','。
My guess is that it doesn't know how to convert the "blah" and "blech" to std::strings. 我的猜测是,它不知道如何将“ blah”和“ blech”转换为std :: strings。 If you construct these explicitly I think it should work.
如果您明确构造这些,我认为它应该起作用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.