您的位置:首页 > 其它

std::for_each()的奇怪现象

2012-10-19 21:14 323 查看
直接晾代码

template<class T1, class T2>

void test(std::pair<T1, T2> pair)

{

pair.second += 1;

}

int _tmain(int argc, _TCHAR* argv[])

{

std::map<int, int> intMap;

std::for_each(intMap.begin(), intMap.end(), &test<int, int>);

system("pause");

return 0;

}

这个可以编译通过,但是改一下

template<class T1, class T2>

void test(std::pair<T1, T2> & pair) //加一个引用

{

pair.second += 1;

}

int _tmain(int argc, _TCHAR* argv[])

{

std::map<int, int> intMap;

std::for_each(intMap.begin(), intMap.end(), &test<int, int>);

system("pause");

return 0;

}

就编译不通过了

再改一下

struct test

{

template<class T1, class T2>

void operator()(std::pair<T1, T2>
& pair)

{

pair.second += 1;

}

};

int _tmain(int argc, _TCHAR* argv[])

{

std::map<int, int> intMap;

std::for_each(intMap.begin(), intMap.end(), test());

system("pause");

return 0;

}

这下可以编译通过了,为什么函数不能传引用,而结构体重载的operator()可以传引用?
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: