2017-11-18 260 views
2

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

如果我明确地使用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中定义的方法定义std冲突与boost库,如std :: bind。提前致谢。

回答

2

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 Phoenix,Boost Spirit boost::spirit::qi::_1std::bind在一起,但是,您可能必须限定占位符。或者,使用您自己的别名。


PS。看起来在这种情况下,您应该可以使用std::mem_fn。如果您使用lambdas _prefer不使用[&],因为这是一种不安全的习惯。在你的情况下,你只需要捕获[this]或如果你想要[=]

+0

嗨!感谢您的回复。使用'_1'可以很好地与boost :: bind配合使用。虽然,如果我要明确使用std :: bind,我应该使用'std :: placeholders :: _ 1'。感谢您指出lambda中的捕获,我会习惯于安全地选择我的捕获。 :) – cawols