#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指向成員函數?
感謝您的反饋
謝謝。一個好的解決方案 – yivo
@Casey我不認爲這是有效的代碼。當GCC接受它時,MSVC2012和Clang 3.0報告錯誤。 –
@Casey下面是一個簡單的例子,不涉及模板,你的方法似乎在做什麼:http://ideone.com/VP1my6。它也無法在GCC上編譯。當你定義'R(T :: pm)()'時,即使'T'是某個類「C」的'const C',並不意味着這樣一個指針可以指向一個const成員'C: :f()const'。你的模板例子被接受看起來像一個編譯器bug。 –