C++。如何将 const_cast 指针指向成员函数?

标签 c++ function pointers 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;
}

我想你已经猜到我在写什么了。是的,我应该用 Func const func 实现 mem_fun_ptr_t<>;属性。这将是正确的解决方案。 但我正在学习,我想知道所有。那么如何const_cast成员函数指针呢? 我试过了 f x = const_cast<f*>(Func)但我收到错误。

感谢您的反馈

最佳答案

同时将成员函数指针的类型传递给您的模板:( 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);
}

关于C++。如何将 const_cast 指针指向成员函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17626102/

相关文章:

java - 在 CNI/C++ 代码中实例化模板类

c++ - 初始检查以查看子字符串是否在范围内

function - 在 gnuplot 中拟合分段函数

c - 结构数组和 malloc [C]

c++ - 在另一个函数/构造函数 [C++] 中初始化后将变量设置为只读

c++ - 从另一个类调用另一个类的函数

python - 如何仅检查 isalpha() 字符串的前 5 个字符?

javascript - 什么是 ES7 异步函数?

c# - C++/CLI 双指针类型转换为 ref IntPtr 以进行 C# 访问

C++将函数指针分配给另一个