c++ - 使用 std::bind 占位符和 boost 库的问题

标签 c++ boost

我使用 boost 库测试框架创建了一个单元测试,并在使用 std::bind 占位符和所述库时遇到了问题。

如果我明确使用 std::placeholders:: + _1,它工作正常:

 std::bind(&TestFixture::concatStrings, this, std::placeholders::_1, std::placeholders::_2)

但是如果我省略 std::placeholders:: 并直接使用 _1,则会导致编译错误:

Error   1   error C2664: 'std::string std::_Pmf_wrap<std::string (__thiscall TestFixture::* )(const std::string &,const std::string &),std::string,TestFixture,const std::string &,const std::string &>::operator ()(_Farg0 &,const std::string &,const std::string &) const' : cannot convert argument 2 from 'boost::arg<1>' to 'const std::string &' C:\APPS\msvs2013\VC\include\functional  1149    1   test

使用 lambda 是我能想到的最好的解决方案:

[&](const std::string& x, const std::string& y){ return concatStrings(x, y); }

我只是想了解使用 std 中定义的方法是否与 boost 库冲突,例如 std::bind。提前致谢。

最佳答案

If I explicitly use std::placeholders:: + _1, it works fine:

因此,如果您正确使用它并且按照文档记录,它就会起作用。

But if I omit the std::placeholders:: and directly use _1, it results to a compilation error:

如果使用不当,它就不起作用。

I just want to understand if using methods defined in std conflicts with boost library, such as the std::bind.

是的,存在命名冲突。本身并没有冲突,但不幸的是 Boost Bind 历史上将它们的占位符放入全局命名空间中。

完全可以使用Boost Bind ::_1 , boost 凤凰, boost spirit boost::spirit::qi::_1std::bind在一起,但是,是的,您可能必须限定占位符。或者,使用您自己的别名。


PS。看起来在这种情况下您应该能够使用 std::mem_fn 。如果您使用 lambda _最好不要使用 [&]因为这是一个不安全的习惯。在您的情况下,您只需要捕获 [this]或者如果您愿意,[=] .

关于c++ - 使用 std::bind 占位符和 boost 库的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47361534/

相关文章:

c# - 从 C# 包装 C++ DLL 的问题

c++ - 将类类型映射到 C++ 中的其他类类型

c++ - Term 不计算为采用三个参数的函数

c++11 - boost、clang 或 gcc 谁失败了?与 boost::asio 一起使用的 std::chrono 的问题

c++ - 加载对象 mtl Direct3D 11

c++ - 如何使静态导入库依赖于CMake中的另一个静态导入库?

c++ - std::bind 函数中没有可行的重载 '='

c++ - boost .python : Argument types did not match C++ signature

c++ - 虚函数和 boost 绑定(bind)奇怪的行为

c++ - 使用相同的前一个词和相同的后一个词读取不同的 QStrings? QString::indexOf