Search code examples
c++functionpointersconst-cast

C++. How can I const_cast pointer to member function?


#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;
}

I think you've already guessed what I'm writing. Yes, I should implement mem_fun_ptr_t<> with Func const func; attribute. And it will be the right solution. But I'm studing and I want to know all. So how to const_cast member function pointer? I've tried f x = const_cast<f*>(Func) but I get errors.

Thanks for your feedbacks


Solution

  • Pass in the type of the member function pointer to your template as well: (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);
    }