不知道为什么字体颜色变不过来,本来强调的部分是用红色标出的,现在只能是灰色的部分,将就着看吧。
先看一段代码:
#include ... // 包含必要的头文件
template <class T1, class T2, class T3>
struct ToFile : binary_function<T1, T2, T3>
{
T3 operator()(T1 p, T2 of)
{
of<<p.first<<": "<<p.second<<endl;
}
};
int main()
{
map<int, int> m; m[1] = 0; m[2] = 0; m[7] = 0;
ofstream of; of.open("times.txt"); for_each(m.begin(), m.end(), bind2nd(ToFile<pair<int,int>,ofstream,void>(), of)); of.close();
}
template <class T1, class T2, class T3>
struct ToFile : binary_function<T1, T2, T3>
{
T3 operator()(T1 p, T2 of)
{
of<<p.first<<": "<<p.second<<endl;
}
};
int main()
{
map<int, int> m;
m[1] = 0;
m[2] = 0;
m[7] = 0;
ofstream of; of.open("times.txt");
for_each(m.begin(), m.end(), bind2nd(ToFile<pair<int,int>,ofstream &,void>(), of)); of.close();
}
继续编译,结果是error C2529: “_Right”: 引用的引用非法
想想是怎么回事,ToFile中的类型是ofstream&,由于bind2nd的模板参数定义是ToFile::second_argument_type&,也就是ToFile::ofstream &&,就是引用的引用,c++中是不允许的,所以编译出错。那怎么办呢?
引用不行,那就用指针来解决吧,代码就变成这个样子:
template <class T1, class T2, class T3>
struct ToFile : binary_function<T1, T2, T3>
{
T3 operator()(T1 p, T2 of)
{
(*of)<<p.first<<": "<<p.second<<endl;
}
};
int main()
{
map<int, int> m;
m[1] = 0;
m[2] = 0;
m[7] = 0;
ofstream of;
of.open("times.txt");
for_each(m.begin(), m.end(), bind2nd(ToFile<pair<int,int>,ofstream*,void>(), &of));
of.close();
}
这下总行了吧,编译有提示错误:error C3848: 具有类型“const ToFile<T1,T2,T3>”的表达式会丢失一些 const-volatile 限定符以调用“void ToFile<T1,T2,T3>::operator ()(T1,T2),晕倒,怎么回事?
原来const类型的变量,只能调用const类型的函数,所以给operator()加上一个const就行了,如下:
template <class T1, class T2, class T3>
struct ToFile : binary_function<T1, T2, T3>
{
T3 operator()(T1 p, T2 of) const
{
(*of)<<p.first<<": "<<p.second<<endl;
}
};