2017-11-18 254 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