读书人

求圣人解答!

发布时间: 2012-11-09 10:18:48 作者: rapoo

求高人解答!!
请问为什么只有Test1是正确的呢,忙活两天了。。。郁闷。。。
本来是用lambda函数写的,以为是编译器支持的问题。改成函数对象也是这样。
求高人解答,小弟在此谢过了。

class Test1
{
public:
template<class T1,class T2>
void operator()(pair<T1,T2> &_pair)
{
_pair.second += 1;
}
};
class Test2
{
public:
template<class T1>
void operator()(pair<T1,T1> &_pair)
{
_pair.second += 1;
}
};
class Test3
{
public:
void operator()(pair<int,int> &_pair)
{
_pair.second += 1;
}
};
int main()
{
std::map<int, int> intMap;
std::for_each(intMap.begin(), intMap.end(), Test1());
std::for_each(intMap.begin(), intMap.end(), Test2());
std::for_each(intMap.begin(), intMap.end(), Test3());

return 0;
}



[解决办法]
map的第一个参数是不可以修改的,其中元素的实际类型是pair<const KEY, VALUE>,

Test1中,你传递进去时,T1其实是 const int,而Test2中,都是同一个类型T1,编译器认为有歧义,无法处理了,Test3也是一样的问题。
改成

void operator()(pair<const T1,T1> &_pair)

void operator()(pair<const int,int> &_pair)

试试

读书人网 >C++

热点推荐