【问题标题】:C++. How can I const_cast pointer to member function?C++。如何将 const_cast 指针指向成员函数?
【发布时间】:2013-07-13 01:29:09
【问题描述】:
#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&lt;f*&gt;(Func),但我得到了错误。

感谢您的反馈

【问题讨论】:

    标签: c++ function pointers const-cast


    【解决方案1】:

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

    【讨论】:

    • 谢谢。一个很好的解决方案。
    • @Casey 我不相信这是有效的代码。虽然 GCC 接受它,但 MSVC2012 和 Clang 3.0 会报告错误。
    • @Casey 这是一个不涉及模板的简单示例,说明您的方法似乎正在执行的操作:ideone.com/VP1my6。它也无法在 GCC 上编译。当你定义R (T::pm)() 时,即使T 是某个类Cconst C,也不意味着这样的指针可以指向一个常量成员C::f() const。接受您的模板示例对我来说就像一个编译器错误。
    • @IgorTandetnik 这就是我在 SO 巡航时喝的酒。替换为实际符合标准的清醒答案。
    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-01-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多