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()可以传引用?
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()可以传引用?
相关文章推荐
- for循环产生的Cortex-M3汇编代码的一个奇怪现象
- cplusplus系列>algorithm>std::for_each
- php for 循环a到z为什么会出现这么奇怪的现象?
- std::for_each && boost bind memer function
- [STL]std::for_each
- std::for_each
- C++中std::for_each的使用
- std::stable_sort 和 std::for_each 的用法[转]
- C++中std::for_each的使用
- 将成员函数作为std::for_each的第三个参数
- c++11,for,for each,std::for_each的应用
- 代码片段----std::for_each
- std 中for_each 算法与c++11范围for语句
- 遇到 'for_each' is not a member of 'std' 的问题
- 利用std::for_each 定义宏函数
- 【C++ STL应用与实现】26: 如何使用std::for_each以及基于范围的for循环 (since C++11)
- std::for_each
- Spark Streaming之妙用foreachRDD和foreachPartition
- Effectiv STL 37 Use accumulate or for_each to summarize ranges
- sp_MSforeachtable使用方法[转]