boost :: bind在std :: transform中连接字符串

pol*_*pts 2 c++ boost boost-bind

我试图在std :: transform内使用boost :: bind连接两个字符串

假设我的类有两个方法来获取两个字符串(第一个和第二个),并且conatiner是字符串向量,我试图做如下

struct Myclass
{
   std::string getFirstString() {return string1}
   std::string getSecondString() {return string2}

   private:
     std::string string1;
     std::string string2;
}

Myclass myObj;

std::vector<string > newVec;
std::vector<myObj> oldVec;
std::transform (oldVec.begin(), oldVec.end(), std::back_inserter(newVec), boost::bind(&std::string::append,boost::bind(&getFirstString,  _1),boost::bind(&getSecondString, _1 ) ) ); 
Run Code Online (Sandbox Code Playgroud)

但是,我得到错误说

error: cannot call member function 'virtual const getSecondString() ' without object
Run Code Online (Sandbox Code Playgroud)

我在这里错过了什么?

Seb*_*edl 6

你有两个问题.

首先是你错误地获取了成员函数的地址.你总是要指定类,即boost::bind(&Myclass::getFirstString, _1).

第二个是你正在尝试绑定std::string::append,它会修改它所调用的对象.你真的想要operator +.由于您无法直接绑定它,请std::plus<std::string>改为使用.所以它应该是这样的:

std::transform(oldVec.begin(), oldVec.end(),
               std::back_inserter(newVec),
               boost::bind(std::plus<std::string>(),
                           boost::bind(&Myclass::getFirstString, _1),
                           boost::bind(&Myclass::getSecondString, _1)
                          )
              );
Run Code Online (Sandbox Code Playgroud)

或者您可以使用Boost.Lambda.当你在它的时候,使用Boost.Range,它真棒.

namespace rg = boost::range;
namespace ll = boost::lambda;
rg::transform(oldVec, std::back_inserter(newVec),
              ll::bind(&Myclass::getFirstString, ll::_1) +
                  ll::bind(&Myclass::getSecondString, ll::_1));
Run Code Online (Sandbox Code Playgroud)