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;
}
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));
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?
[EDIT] 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?
[EDIT2]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));
See Question&Answers more detail:
os