c++ - 我可以安全地将指向 const 成员的指针转换为相同类型但非常量吗?

标签 c++ c++11 pointer-to-member member-pointers

...即使pointers to member functions are strange animals

我正在编写一个库以将 C++ 类绑定(bind)到 Lua。我必须处理将某些类型的对象插入 Lua 堆栈(并将它们转换为 void*)而导致的类型删除。出于这个原因,也是为了避免不同类型数据的不同模板过度扩散(非 const 和 const 对象,非 const 和 const 成员,以及将来将 volatile 和 non volatile 的一切加倍......),我管理通过简单地设置特定标志,在运行时绑定(bind)到 Lua 的对象的常量性。

现在,我正在处理指向成员函数的指针。按照我目前的设计,如果我可以安全地将指向 const 成员函数的指针转换为非常量成员函数,然后为非常量重用相同的模板,并在运行时使用上述标志处理 const 性,我会很高兴。

但是还有另一个提示让我怀疑这是否真的可能。考虑以下代码:

#include <iostream>
#include <typeinfo>
using namespace std;

struct A{
    const int a;
    int b;
};

template<typename T> struct tmpl;

template<typename Class, typename FT> struct tmpl<FT(Class::*)>{
    static void f(){
        cout<<"non const"<<endl;
    }
};

//Try commenting this out, code compiles, both A::a and A::b instantiate the first template
template<typename Class, typename FT> struct tmpl<const FT(Class::*)>{
    static void f(){
        cout<<"const"<<endl;
    }
};

int main(){
    cout<<typeid(&A::a).name()<<endl;   //prints "M1AKi"
    tmpl<decltype(&A::a)>::f();         //prints "const"
    cout<<typeid(&A::b).name()<<endl;   //prints "M1Ai"
    tmpl<decltype(&A::b)>::f();         //prints "non const"
    //Let's do what it seems that can be done implicitly (providing only one template specialization) in an explicit way
    int(A::*memb)=(int(A::*))&A::a;
    cout<<typeid(memb).name()<<endl;    //prints "M1Ai"
    tmpl<decltype(memb)>::f();          //prints "non const"
}

看来不管these animals can even change their own size ,在某些情况下,您可以安全地将它们转换(或者至少 const_cast)为其他类型(如果它们有意义的话)。

那么,我的推理是否在其中一个步骤中严重错误,或者我可以这样做,而不管编译器如何?我可以用指向 const 成员函数的指针来玩同样的游戏吗?

最佳答案

在“非常量”特化中,FT 被简单地推导为包含 const 限定符。它不会消失,只是传入。

试试这个:

template<typename Class, typename FT> struct tmpl<FT(Class::*)>{
    static void f(){
        if ( std::is_const< FT >::value ) {
            cout<<"const as non const"<<endl;
        } else {
            cout<<"non const"<<endl;
        }
    }
};

http://ideone.com/g2Eie

如果你想杀死一个 const,那么 const_cast 是唯一可行的工具。

关于c++ - 我可以安全地将指向 const 成员的指针转换为相同类型但非常量吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10063259/

相关文章:

c++ - std::ofstream == NULL 不会为 -std=gnu++11 编译,任何解决方法?

c++ - 在 C++ 中,(int *) 和 & 有什么区别?

c++ - 使用指向成员的指针时,如何通过作用域解析运算符获取类成员的地址?

c++ - C++ 中一般树实现的问题

c++ - 为什么不能在 C++11 中将非虚拟方法定义为 final?

visual-studio - 我正在上一门类(class),但讲师说的东西行不通

c++ - API 内存 : Heap or Stack? (C++)

c++ - Swift 使用静态库编译源作为 Objective-C++

c++ - rethrow_exception 真的可以抛出相同的异常对象,而不是一个拷贝吗?

c++ - 混合代码 - 函数成员指针