我可以安全地将指向 const 成员的指针转换为相同类型但非常量
can I safely cast a pointer to const member to the same type but non-const?
...即使指向成员函数的指针是奇怪的动物?
我正在编写一个库以将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
是这项工作唯一可行的工具。
相关文章:
- 如何修复函数样式强制转换或类型构造的预期"("?
- 为 Sql 服务器实现 odbc 包装器.将数据库数据读取为字符或要求驱动程序将数据转换为 C 类型
- Zedboard zynq-7000 Opencl 浮点数从类型 'double*' 强制转换为类型 'double' 无效
- std::函数指针错误:无法将 &A::a 转换为类型 std::function<>&&
- 使用用户定义的操作隐式转换为类型
- 将函数应用于元组中的每个元素,将每个元素强制转换为类型包中的不同类型,然后作为参数包传递
- 如何转换不同类型的迭代器
- 将fwrite转换为C++类型代码以写入二进制文件
- C++将字符串转换为类型名称
- 从单独的库中隐式强制转换相似类型,以便在C++中无缝协作
- 表达式到C++类类型转换器/类型转换
- 将 2D 矢量转换为 C 类型的最佳方法(适用于 SGX 飞地)
- 模拟返回具有多个用户定义转换的类型的方法
- 如何将C++ ulong 4 字节 IP 地址正确转换为 C# 类型
- 是否可以将 Dword 转换为类型名称
- 从类模板中排除转换运算符...<类型名 T>基于 T 上的特征
- 初始化中的模板转换运算符类型推导规则是什么?
- 转换指针类型
- 如何在Cython中将Python对象转换为C++类型
- 使用模板转换特定类型的参数