![](/img/trans.png)
[英]C++: passing the template callback method into the other method: cannot convert ‘<unresolved overloaded function type> to pointer
[英]Pointer to template method gives <unresolved overloaded function type>)
我已经读过许多类似问题的问题,但是大多数时候,他们会归结为使用函数指针而不是方法指针,或者在创建指针实例时忽略类范围的人们。 但是我什么都不做(我认为...):
class Test
{
public:
Test() { mFuncPtrs.insert( 10, &Test::Func<int> ); } // Error!
template <class T>
void Func() {}
private:
typedef void ( Test::*FuncPtr )();
std::map<int, FuncPtr> mFuncPtrs;
};
但这给出了:
error: no matching function for call to ‘std::map<int, void (Test::*)(), std::less<int>, std::allocator<std::pair<const int, void (Test::*)()> > >::insert(int, <unresolved overloaded function type>)’
但是我对模板类型很明确,提供了方法的全部范围,并且Func()
没有重载! 如果有什么不同,我正在使用g ++ v4.1.2。
您错误地使用了std::map
的insert()
函数。 insert()
没有将键和值作为两个独立参数的重载。
相反,您需要在键和值的std::pair
上调用它:
mFuncPtrs.insert(std::make_pair(10, &Test::Func<int>) );
或者,在C ++ 11中,可以对使用统一的初始化语法:
mFuncPtrs.insert( { 10 , &Test::Func<int> } );
不过,最简单的方法是完全避免使用insert()
而只使用索引运算符:
mFuncPtrs[10] = &Test::Func<int>;
更好的是,鉴于所有这些都发生在构造函数中,即在映射的初始化时间,同样在C ++ 11中,您可以使用所需的对来初始化映射:
class Test
{
public:
Test()
: mFuncPtrs { { 10 , &Test::Func<int> } }
{ }
/* ... */
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.