c++ - static_assert 向上转换是否需要调整指针

标签 c++ inheritance multiple-inheritance

我想执行编译时检查,检查从派生类型到基类型的向上转换是否需要指针调整。我没有从 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 paperissue 。指针可互转换类型具有相同的地址,并且它们的指针可以通过 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/

相关文章:

c++ - 从构造函数中抛出异常

c# - 当父类也实现 IDisposable 时在子类上实现 IDisposable

Java 数据层次结构和行映射

inheritance - 协议(protocol)类型对象的 Swift 数组

c++ - 多重继承 : unexpected result after cast from void * to 2nd base class

c++ - 如何从进程中获取实时、非阻塞的输出

c++ - 有没有办法在函数调用中通过引用传递和通过值显式传递?

c++ - 返回数字中的数字的函数

C++ 多重继承关闭同名运算符

python - Python 的 super() 如何与多重继承一起工作?