问题描述
我仍然在学习c ++ 11的功能,如何正确使用绑定。这是一个实验:
I am still learning c++11 features around how to use bind properly. Here is an experiment:
using namespace std::placeholders;
using namespace std;
struct MyType {};
ostream& operator<<(ostream &os, const MyType &n)
{
os << n;
return os;
}
int main()
{
std::vector<MyType> vec;
std::for_each(vec.begin(), vec.end(), std::bind(operator<<, std::ref(std::cout), _1));
return 0;
}
我得到clang编译错误:
I get clang compile error:
error: no matching function for call to 'bind'
std::for_each(vec.begin(), vec.end(), std::bind(operator<<, std::ref(std::cout), _1));
我想bind不能区分函数运算符<<
I guess bind cannot distinguish the function operator<< defined in my file from those pre-defined.
但我不知道它是否可以做,只是我做错了吗?
But I wonder if it actually can be done and just I did it wrong?
感谢ISARANDI,prefixing ::修复了问题。但是如何在同一个命名空间我有重载的函数:
Thanks ISARANDI, prefixing :: fixed the problem. But how about at the same namespace I have overloaded functions:
using namespace std::placeholders;
using namespace std;
struct MyType {};
struct MyType2 {};
ostream& operator<<(ostream &os, const MyType &n)
{
os << n;
return os;
}
ostream& operator<<(ostream &os, const MyType2 &n)
{
os << n;
return os;
}
int main()
{
std::vector<MyType> vec;
std::for_each(vec.begin(), vec.end(), std::bind(::operator<<, std::ref(std::cout), _1));
return 0;
}
在这种情况下,即使使用全局命名空间,我仍然会遇到编译错误。 。
In this case, I still get that compile error even with the global namespace.. Is there a solution here?
好的,想出来,我需要把它:
OK, figured out, I need to cast it:
std::for_each(vec.begin(), vec.end(), std::bind((ostream&(ostream&, const MyType&))::operator<<, std::ref(std::cout), _1));
推荐答案
因为 using namespace std ;
运算符<<
有多个重载。
要显式选择您的版本,请写
Because of using namespace std;
operator<<
has multiple overloads.In order to explicitly select your version, write
std::for_each(vec.begin(), vec.end(), std::bind(::operator<<, std::ref(std::cout), _1));
前缀 ::
全局命名空间。
这篇关于我可以使用stream运算符绑定吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!