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

can I safely cast a pointer to const member to the same type but non-const?

本文关键字:转换 同类型 常量 非常 指针 安全 成员 const 我可以      更新时间:2023-10-16

...即使指向成员函数的指针是奇怪的动物?

我正在编写一个库以将C++类绑定到 Lua。我必须处理由于将某些类型对象推到 Lua 堆栈上而导致的类型擦除(因此将它们转换为 void*)。出于这个原因,也为了避免不同类型数据(non const 和 const 对象、non const 和 const 成员,以及将来将易失性和非可变性的所有内容加倍......)的不同模板过度扩散,我通过简单地设置某个标志来管理运行时绑定到 Lua 的对象的恒定性。

现在,我正在处理指向成员函数的指针。按照我到目前为止的设计,如果我能安全地将指向 const 成员函数的指针投射到非 const 函数,然后对 non-const 重用相同的模板,并在运行时使用上述标志处理 constness,我会很高兴。

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

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

似乎无论这些动物甚至可以改变自己的大小,在某些情况下,您都可以安全地将它们投射(或至少const_cast)到其他类型的动物(如果它们有意义的话)。

那么,我的推理在其中一个步骤中是否严重错误,或者我可以这样做,无论编译器如何?我可以以同样的方式使用指向 const 成员函数的指针吗?

在"non-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是这项工作唯一可行的工具。