mem_func 和虚函数
我有以下课程:
class A
{
public:
virtual void myfunc(unsigned char c, std::string* dest) = 0;
};
class B : public class A
{
public:
virtual void myfunc(unsigned char c, std::string* dest);
};
void someOtherFunc(const std::string& str,A *pointerFunc)
{
std::string tmp;
for_each(str.begin(),
str.end(),
std::bind2nd(std::mem_fun(pointerFunc->myfunc), &tmp));
}
我收到以下编译错误: 错误:没有匹配的函数来调用 \u2018mem_fun()\u2019
你知道为什么吗?
I have the following classes:
class A
{
public:
virtual void myfunc(unsigned char c, std::string* dest) = 0;
};
class B : public class A
{
public:
virtual void myfunc(unsigned char c, std::string* dest);
};
void someOtherFunc(const std::string& str,A *pointerFunc)
{
std::string tmp;
for_each(str.begin(),
str.end(),
std::bind2nd(std::mem_fun(pointerFunc->myfunc), &tmp));
}
I get the following compilation error:
error: no matching function for call to \u2018mem_fun()\u2019
Do you know why?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您正在寻找std::mem_fun(&A::myfunc)
。编辑:您在这里根本无法使用
mem_fun
-- 没有重载mem_fun
允许您将两个参数的成员函数变成函子。您将必须使用类似boost::bind
/std::tr1::bind
(如果您有 TR1)/std::bind
(如果您有 C++0x)或者您将不得不编写自己的函子。请注意,即使
mem_fun
能够执行这种绑定,std::bind2nd
也会失败,因为bind2nd
期望函子需要两个参数,并像这样绑定成员函数指针将生成一个具有三个参数的函子。您有几种方法可以解决此问题:
std::for_each
。myfunc
不依赖于其所属类的成员的情况下才有效(在这种情况下,它一开始就不应该被放入类中)You're looking forstd::mem_fun(&A::myfunc)
.EDIT: You can't use
mem_fun
at all here -- no overload ofmem_fun
allows you to make a two argument member function into a functor. You're going to have to use something likeboost::bind
/std::tr1::bind
(If you have TR1)/std::bind
(If you have C++0x) or you're going to have to write your own functor.Note that even if
mem_fun
was able to do this sort of binding, thenstd::bind2nd
would fail, becausebind2nd
expects a functor taking two arguments, and binding a member function pointer like this is going to produce a functor with three arguments.You have a few ways around this:
std::for_each
.myfunc
doesn't depend on members of the class to which it belongs (in which case it shouldn't have ever been put into a class in the first place)您在这里尝试使用的是使用指向成员函数的指针来应用容器中每个对象的另一个对象的成员函数。显然,在这种情况下,任何适配器都不起作用。在这种情况下,唯一的解决方案是为其编写一个特殊的包装函子类。
What you are trying to use here is use a pointer to a member function to apply a member function of another object to every object in the container. Apparently none of the adapters will work in this case. In that case the only solution is to write a special wrapper functor class for it.
查看 std::mem_fun 背后的实现,您应该能够编写自己的:
编辑(使其“人类可读”)
Looking at the implementation behind of std::mem_fun you should be able to write your own:
EDIT (made it "human-readable")
您的声明并不代表您想要做什么。
尝试:
这个(或其变体)应该可以满足您的需求。
Your declaration does not represent what you want to do.
try:
this (or a variation of) should do what you want.