问题描述
如果我有一个具有多个基数的派生类,则每个基数的每个this指针都将与派生对象的this指针不同,唯一不同的是.给定继承层次结构中的两种类型,我想在编译时检测它们是否共享相同的this指针.像这样的东西应该可以,但不能:
If I have a derived class with multiple bases, each this pointer for each base will be different from that of the derived object's this pointer, except for one. Given two types in an inheritance hierarchy, I'd like to detect at compile time whether they share the same this pointer. Something like this should work, but doesn't:
BOOST_STATIC_ASSERT(static_cast<Base1*>((Derived *)0xDEADBEEF) == (Derived*)0xDEADBEEF);
因为它必须是一个整数常量表达式",并且在根据标准的那些整数转换中仅允许使用整数转换(这是愚蠢的,因为如果不使用虚拟继承,它们仅需要编译时间信息).尝试将结果作为整数模板参数传递时,会发生相同的问题.
Because it needs to be an 'integral constant expression' and only integer casts are allowed in those according to the standard (which is stupid, because they only need compile time information if no virtual inheritance is being used). The same problem occurs trying to pass the results as integer template parameters.
我能做的最好的事情是在启动时检查,但是我需要在编译期间提供信息(以使一些深层次的模板黑客能够正常工作).
The best I've been able to do is check at startup, but I need the information during compile (to get some deep template hackery to work).
推荐答案
我正在尝试解决这个完全相同的问题.如果您知道基类布局的开头是什么成员变量,则我有一个可行的实现.例如.如果在每个类的开头都存在成员变量"x",则以下代码将从派生类布局中产生特定基类布局的字节偏移量:offsetof(derived,base2 :: x).
I am trying to solve this exact same issue. I have an implementation that works if you know what member variable is at the beginning of the base class's layout. E.g. if member variable "x" exists at the start of each class, then the following code will work to yield the byte offset of a particular base class layout from the derived class layout: offsetof(derived, base2::x).
在以下情况下:struct base1 { char x[16]; };
struct base2 { int x; };
struct derived : public base1, public base2 { int x; };
static const int my_constant = offsetof(derived, base2::x);
In the case of:struct base1 { char x[16]; };
struct base2 { int x; };
struct derived : public base1, public base2 { int x; };
static const int my_constant = offsetof(derived, base2::x);
编译器将为我的体系结构(x86_64)上的my_constant正确分配"16".
The compiler will properly assign "16" to my_constant on my architecture (x86_64).
困难是当您不知道基类布局的开头是什么成员变量时获得"16".
The difficulty is to get "16" when you don't know what member variable is at the start of a base class's layout.
这篇关于C ++,静态检测具有不同地址的基类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!