gpt4 book ai didi

c++ - 根据标准,这个 constexpr offset_of 的定义是否正确?

转载 作者:太空狗 更新时间:2023-10-29 22:57:59 25 4
gpt4 key购买 nike

我想知道这个 constexpr offset_of 的定义是否符合 c++11 标准。

根据 this article , C++98 允许在数组声明中进行转换。我调整了文章中的代码以允许我的一些案例。我可以执行以下操作吗?如果不行,有没有更好的办法?

template<typename T>
struct declval_helper { static T value; };

template<typename T, typename Z, typename U, Z U::*MPtr>
struct offset_helper {
using TV = declval_helper<T>;

static char for_sizeof[1 + (
(char *)&(TV::value.*MPtr) -
(char *)&TV::value
)];
};

template<typename T, typename Z, typename U, Z U::*MPtr>
constexpr std::size_t offset_of() {
return sizeof(detail::offset_helper<T, Z, U, MPtr>::for_sizeof) - 1;
}

一个用例:

struct Base { int data; };
struct Derived : Base { float data; };

constexpr std::size_t offset = offset_of<Derived, int, Base, &Base::data>();

最佳答案

不,它的格式不正确。

来自 [dcl.array]:

If the constant-expression (5.20) is present, it shall be a converted constant expression of type std::size_t and its value shall be greater than zero.

这里的constant-expression指的是数组绑定(bind),可选。转换后的常量表达式来自 [expr.const]:

A converted constant expression of type T is an expression, implicitly converted to type T, where the converted expression is a constant expression [...]

常量表达式是:

A conditional-expression e is a core constant expression unless the evaluation of e, following the rules of the abstract machine (1.9), would evaluate one of the following expressions: [...] — a reinterpret_cast (5.2.10);

本声明:

static char for_sizeof[1 + (
(char *)&(TV::value.*MPtr) -
(char *)&TV::value
)];

在数组的数组边界中使用隐式 reinterpret_cast,这使得它不是常量表达式,因此它是病式的。

关于c++ - 根据标准,这个 constexpr offset_of 的定义是否正确?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42100976/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com