2013-07-13 14 views
2
#include <iostream> 

template <typename Type, typename ReturnType> 
struct mem_fun_ptr_t 
{ 
    typedef ReturnType (Type::*Func)(); 
    Func func; 
public: 
    mem_fun_ptr_t(Func f): 
     func(f) {} 
    ReturnType operator() (Type *p) { return (p->*func)(); } 
}; 

// non-const version 
template <typename T, typename R> 
mem_fun_ptr_t<T, R> mem_fun_ptr(R (T::*Func)()) 
{ 
    return mem_fun_ptr_t<T, R>(Func); 
} 

// const version 
template <typename T, typename R> 
mem_fun_ptr_t<T, R> mem_fun_ptr(R (T::*Func)() const) 
{ 
    typedef R (T::*f)(); 
    f x = const_cast<f>(Func); //error 
    return mem_fun_ptr_t<T, R>(x); 

    //but this works: 
    /* 
    f x = reinterpret_cast<f>(Func); 
    return mem_fun_ptr_t<T, R>(x); 
    */ 
} 

int main() 
{ 
    std::string str = "Hello"; 
    auto x = mem_fun_ptr(&std::string::length); 
    std::cout << x(&str); 
    return 0; 
} 

我想你已經猜到了我在寫什麼。是的,我應該用Func const func實現mem_fun_ptr_t <>;屬性。這將是正確的解決方案。 但我正在學習,我想知道所有。那麼如何const_cast成員函數指針呢? 我試過f x = const_cast<f*>(Func)但我得到錯誤。C++。我如何const_cast指向成員函數?

感謝您的反饋

回答

2

通行證在成員函數指針到您的模板類型以及:(Live at ideone.com):

template <typename Type, typename ReturnType, typename MemFuncType> 
struct mem_fun_ptr_t 
{ 
    MemFuncType func; 
public: 
    mem_fun_ptr_t(MemFuncType f) : 
     func(f) {} 
    ReturnType operator() (Type *p) const { return (p->*func)(); } 
}; 

// non-const version 
template <typename T, typename R> 
mem_fun_ptr_t<T, R, R (T::*)()> 
mem_fun_ptr(R (T::*Func)()) 
{ 
    return mem_fun_ptr_t<T, R, R (T::*)()>(Func); 
} 

// const version 
template <typename T, typename R> 
mem_fun_ptr_t<const T, R, R (T::*)() const> 
mem_fun_ptr(R (T::*Func)() const) 
{ 
    return mem_fun_ptr_t<const T, R, R (T::*)() const>(Func); 
} 
+0

謝謝。一個好的解決方案 – yivo

+0

@Casey我不認爲這是有效的代碼。當GCC接受它時,MSVC2012和Clang 3.0報告錯誤。 –

+0

@Casey下面是一個簡單的例子,不涉及模板,你的方法似乎在做什麼:http://ideone.com/VP1my6。它也無法在GCC上編譯。當你定義'R(T :: pm)()'時,即使'T'是某個類「C」的'const C',並不意味着這樣一個指針可以指向一個const成員'C: :f()const'。你的模板例子被接受看起來像一個編譯器bug。 –

3

你不能const_cast一個成員指針這種方式。而reinterpret_cast在技術上表現出未定義的行爲。正是由於這個原因,標準庫包含單獨的mem_fun_tconst_mem_fun_t類,其中mem_fun重載製造一個或另一個。