C ++. Как я могу const_cast указатель на функцию-член?

#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<> с Func const func; приписывать. И это будет правильным решением.
Но я учусь и хочу все знать. Так как же указатель на функцию-член const_cast?
я пробовал f x = const_cast<f*>(Func) но я получаю ошибки.

Спасибо за ваши отзывы

3

Решение

Также передайте тип указателя на функцию-член в шаблон: (Жить на 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);
}
3

Другие решения

Ты не можешь const_cast указатель на член таким образом. А также reinterpret_cast технически проявляет неопределенное поведение. Именно по этой причине стандартная библиотека содержит отдельные mem_fun_t а также const_mem_fun_t классы, с перегрузками mem_fun, производящими один или другой.

3