我想执行编译时检查,检查从派生类型到基类型的向上转换是否需要指针调整。我没有从 type_traits
中看到任何可以使用的内容。这可以吗?
下面是如何在运行时完成此操作的示例。请注意,clang 甚至警告第一个 printf
永远不会打印“yes”,第二个永远不会打印“no”,因此它确实将这些调整值评估为常量。问题是,如何在编译时访问这些值?
#include <stdio.h>
struct A
{
int a;
};
struct B
{
int b;
};
struct C: A, B
{
int c;
};
int main()
{
C c;
// Prints "no"
printf( "Is pointer adjustment required when casting from C to A? %s\n",
( ( char * ) ( A * ) &c - ( char * ) &c ) ? "yes" : "no" );
// Prints "yes"
printf( "Is pointer adjustment required when casting from C to B? %s\n",
( ( char * ) ( B * ) &c - ( char * ) &c ) ? "yes" : "no" );
// Can we have those values as constexpr though?
return 0;
}
最佳答案
这称为指针可互换性。有一个特质std::is_pointer_interconvertible_base_of
不幸的是,它尚未在 gcc 和 clang 中实现。另请参阅the paper和 issue 。指针可互转换类型具有相同的地址,并且它们的指针可以通过 reinterpret_cast
进行转换。
#include <type_traits>
#ifdef __cpp_lib_is_pointer_interconvertible
// Prints "no"
printf( "Is pointer adjustment required when casting from C to A? %s\n",
std::is_pointer_interconvertible_base_of_v<A, C> ? "no" : "yes" );
// Prints "yes"
printf( "Is pointer adjustment required when casting from C to B? %s\n",
std::is_pointer_interconvertible_base_of_v<B, C> ? "no" : "yes" );
#endif
关于c++ - static_assert 向上转换是否需要调整指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68449351/