#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)
,但我得到了错误。
感谢您的反馈