3
#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),但我得到了错误。

感谢您的反馈

4

2 回答 2

3

您不能const_cast以这种方式指向成员。并且在reinterpret_cast技术上表现出未定义的行为。正是出于这个原因,标准库包含单独的mem_fun_tconst_mem_fun_t类,而 mem_fun 重载制造了其中一个或另一个。

于 2013-07-13T01:45:03.853 回答
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);
}
于 2013-07-13T05:10:35.417 回答