我可以在bind中使用流操作符吗?
Can I use stream operator with bind?
我还在学习如何正确使用bind的c++11特性。下面是一个实验:
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编译错误:
error: no matching function for call to 'bind'
std::for_each(vec.begin(), vec.end(), std::bind(operator<<, std::ref(std::cout), _1));
我猜bind不能区分函数operator<<在我的文件中定义的那些预定义的。
但我想知道这是否真的可以做到,只是我做错了吗?
[编辑]谢谢ISARANDI,前缀::修复了这个问题。但是,如果在同一个命名空间我有重载函数:
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;
}
在这种情况下,即使使用全局命名空间,我仍然会得到编译错误。这里有解决方案吗?
[EDIT2]好的,我明白了,我需要转换它:
std::for_each(vec.begin(), vec.end(), std::bind((ostream&(ostream&, const MyType&))::operator<<, std::ref(std::cout), _1));
由于using namespace std;
, operator<<
有多个过载。要显式选择您的版本,请写入
std::for_each(vec.begin(), vec.end(), std::bind(::operator<<, std::ref(std::cout), _1));
前缀by ::
从全局命名空间中选择过载
相关文章:
- POCO::PostgreSQL:如何将std::vector支持添加到`Binder::bind`
- boost::bind()类似的东西,但用于函数调用
- 使用 std::应用于 std::bind
- PCL:当我在setConditionFunction中使用std::bind 时,没有合适的转换函数
- std::bind on statd::array 的运算符 []
- std::bind c++ in if statement
- std::bind 是否实现了 std::ref 和 std::cref 来消除函数调用的歧义?
- C++ 事件管理器的回调,使用 std::function 和 std:bind 以及派生类作为参数
- 试图克服 std::bind 编译错误
- c++ std::bind within function
- std::bind to void* to std::function
- std::bind,无法让具有单个参数的方法工作
- std::bind 和 std::函数术语不值为接受 0 个参数?
- 在调用 std::bind 的产品后意外调用析构函数
- 使用 object 中的方法调用带有 std::bind 和 std::function.target 的 C 样式函数
- 我们应该在使用 std::bind 应用之前检查一个不为空的函数吗?
- 为什么 std::bind 静态类型检查传递给函数的参数?
- 对函数库中的语法感到困惑 std::bind
- Boost::bind重载操作符导致Boost未定义引用错误
- 我可以在bind中使用流操作符吗?