簡體   English   中英

為什么成員函數mem_fun調用必須是const一個?

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

mem_funmem_fun_ref以及許多其他成員函數適配器可以使成員函數的行為類似於普通函數。 但是有一個限制,即它們調用的成員函數必須是const函數 我知道如何使用它們,但對其背后的原因感到困惑和困惑。 為什么以這種方式設計?

更新:抱歉,含糊。 在下面寫一個例子。

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));
...

沒有這樣的限制。 這些模板函數對於const和non-const成員函數都是重載的。

例如

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