C++ c++;-绑定运算符=std::string的成员
我有一个类(我们称之为C++ c++;-绑定运算符=std::string的成员,c++,functor,C++,Functor,我有一个类(我们称之为myclass)。它的一个私有成员变量是一个名为myfunctor的std::function,返回类型为bool,它有两个参数: bool myfunction (const std::string & input, std::string & output) { output = input; } myclass的构造函数应接收对输出std::string的引用作为其唯一参数,因此初始化它的方法如下: myclass::myclass
myclass
)。它的一个私有成员变量是一个名为myfunctor
的std::function
,返回类型为bool
,它有两个参数:
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=),占位符::\u 1
等等,但是编译器(GCC 4.8.0)给了我一些错误,比如
没有匹配项转换为…
为了指定要使用的std::string::operator=
的重载(有多个)。此外,您需要这个成员函数作用的对象(=成员函数中使用的此指针)
或者,如果您真的需要返回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;
}
#包括
#包括
#包括
int main()
{
std::string mystring;
函数f=
[&mystring](std::string const&rhs)->bool{mystring=rhs;return true;};
f(“你好世界”);
std::cout您是否打算=
成为=
?我认为您必须指定重载,因为std::string::operator=
有几个重载。但是您是否知道,如果传递给myclass::myclass
的对象已被销毁,则在bind
中存储引用可能会留下一个悬空引用?@bopers关于否,我的意思是=
。我想赋值,而不是比较。@DyP怎么做?我尝试了几种方法,但编译器仍然抱怨无法解决的重载。为什么不使用lambda呢?它简单得多。它一直在抱怨。请记住,我的std::function
必须是std::function
。把你发布的内容放进去会让GCC说,没有匹配的函数来调用…
-好的,对不起,我刚刚意识到std::string::operator=
不会返回bool
,这将很难解决,所以我应该继续使用包装器。为什么你的函数返回bool?应该返回什么?std::string::operator=
返回*此
,即赋值左侧的字符串lhs=rhs
@Kalrish您可以有另一个间接级别(另一个对bind
的调用)要将std::string
转换为bool
,那有什么用呢?您会返回什么,总是true
?该函数应该是某种转换器。这是最简单的一个(没有进行转换),但我可以实现另一个映射,比如说,带有布尔值的字符串(即true
,false
,等等)。通过返回true
或false
,“translator”函数将告诉调用方是否可以进行翻译(例如,我希望打开
或关闭
,并且我收到foobar
;这将返回false
)。当您可以首先使用正确的lambda时,为什么要用std::bind
修改lambda行为?[&mystring](std::string const&rhs)->bool{mystring=rhs;return true;};
#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;
}