我正在使用c++11特性,并尝试了以下代码:
void dump(ostream &os, const MyType &mt)
{
}
void f(const vector<MyType> &mts, ostream &os)
{
for_each(mts.begin(), mts.end(), bind(dump, ref(os), ref(_1));
}
这段代码在clang编译时出现错误:
/usr/bin/../lib/gcc/x86_64-linux-gnu/4.8/../../../../include/c++/4.8/bits/stl_algo.h:4417:2: error: no matching function for call to object of type
'std::_Bind<void (*(std::reference_wrapper<std::basic_ostream<char> >, std::reference_wrapper<const std::_Placeholder<1> >))(std::basic_ostream<char>
&, const MyType &)>'
__f(*__first);
如果我从_1
中删除ref
,它就可以正常编译:
for_each(mts.begin(), mts.end(), bind(dump, ref(os), _1);
似乎占位符不适用于引用,但希望确认一下,您能列出它为什么不适用的语义定义吗?它实际上已经通过引用传递了吗?
bind
不相关(这里就是这种情况),要么它非常复杂,使bind
起作用将需要太多的工作。使用基于范围的循环,只需调用函数即可。 - Cheers and hth. - Alffor_each(mts.begin(), mts.end(), [&os](const MyType &x) { dump(os, x); });
- rodrigo