简体   繁体   English

为什么成员函数mem_fun调用必须是const一个?

[英]why the member function mem_fun calls must be a const one?

mem_fun and mem_fun_ref and many other member function adaptors can make member functions act like orindinary functions. mem_funmem_fun_ref以及许多其他成员函数适配器可以使成员函数的行为类似于普通函数。 But there is one restriction that the member function that they call must be a const one. 但是有一个限制,即它们调用的成员函数必须是const函数 I get to know how to use them, but confused and puzzled by the reasons behind it. 我知道如何使用它们,但对其背后的原因感到困惑和困惑。 Why is it designed in this way? 为什么以这种方式设计?

update: Sorry for the ambiguity. 更新:抱歉,含糊。 write an example below. 在下面写一个例子。

class A
{
    ...
    //void fun(){cout<<"Fun";} This is not const and the compiler would complain
    void fun() const {cout<<"Not fun";}
    ...
}
vector<A> avec;
...
for_each(avec.begin(),avec.end(),mem_fun_ref(&A::fun));
...

There is no such a restriction. 没有这样的限制。 These template functions are overloaded for const and non-const member functions. 这些模板函数对于const和non-const成员函数都是重载的。

For example 例如

template<class S, class T>
mem_fun_t<S,T> mem_fun(S (T::*f)());

template <class S, class T>
const_mem_fun_t<S,T> mem_fun(S (T::*f)() const);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM