直接晾代码
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()可以传引用?
本文探讨了C++中使用模板函数与结构体成员函数处理std::pair引用时的编译差异。通过对比不同实现方式的编译结果,揭示了模板函数在传递引用时的局限性及其解决方案。

362

被折叠的 条评论
为什么被折叠?



