#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;
}
我想你已经猜到了我在写什么。是的,我应该实现mem_fun_ptr_t&lt;&gt;用Func const func;属性。这将是正确的解决方案。
但我正在学习,我想知道所有。那么如何使用const_cast成员函数指针?
我试过f x = const_cast<f*>(Func)
,但我收到了错误。
感谢您的反馈
答案 0 :(得分:3)
你不能const_cast
以这种方式指向成员的指针。并且reinterpret_cast
在技术上表现出未定义的行为。正是由于这个原因,标准库包含单独的mem_fun_t
和const_mem_fun_t
类,mem_fun重载制造了一个或另一个。
答案 1 :(得分:3)
将成员函数指针的类型传递给模板:(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);
}