我使用 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::_1
和std::bind
在一起,但是,是的,您可能必须限定占位符。或者,使用您自己的别名。
PS。看起来在这种情况下您应该能够使用
std::mem_fn
。如果您使用 lambda _最好不要使用 [&]
因为这是一个不安全的习惯。在您的情况下,您只需要捕获 [this]
或者如果您愿意,[=]
.
关于c++ - 使用 std::bind 占位符和 boost 库的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47361534/