我有一个类(我们称之为myclass
(。它的一个私有成员变量是一个名为myfunctor
的返回类型为bool
的std::function
,它接受两个参数:
bool
myfunction
(const std::string & input, std::string & output)
{
output = input;
}
myclass
的构造函数应接收对输出std::string
的引用,作为其唯一的参数,因此初始化它的方法如下:
myclass::myclass
(std::string & s)
: myfunctor( std::bind(myfunction, std::placeholders::_1, s) )
{
return;
}
但是,我希望有一种方法可以直接使用std::string
中的operator=
。但我仍然没有找到它。我尝试了许多不同的组合,但没有运气:
std::bind( (std::string & (std::string::*) (std::string &)) &(s.operator=), placeholders::_1
等等,但编译器(GCC 4.8.0(给了我类似no matches converting to ...
的错误。
您需要进行强制转换,以便指定要使用的std::string::operator=
的重载(有多个(。此外,您需要成员函数作用的对象(=成员函数中使用的this
指针(。
或者,如果您真的需要返回一个bool,您可以将调用封装在lambda:中
#include <iostream>
#include <string>
#include <functional>
int main()
{
std::string mystring;
std::function<bool(std::string const&)> f =
[&mystring](std::string const& rhs)->bool { mystring = rhs; return true; };
f("hello world");
std::cout << mystring << std::endl;
}
具有明确过载解决方案的版本:
#include <iostream>
#include <string>
#include <functional>
int main()
{
// nice C++11 syntax
using assignment_FPT = std::string& (std::string::*)(std::string const&);
// in case your compiler doesn't know that yet
//typedef std::string& (std::string::*assignment_FPT)(std::string const&);
std::string mystring;
auto f = std::bind(
static_cast<assignment_FPT>(&std::string::operator=),
std::ref(mystring), // either `ref` or a pointer (or it will be copied)
std::placeholders::_1);
f("hello world");
std::cout << mystring << std::endl;
}