gpt4 book ai didi

c++ - 使用 alignas 进行参数包扩展的语法是什么?

转载 作者:搜寻专家 更新时间:2023-10-31 02:21:07 26 4
gpt4 key购买 nike

我正在尝试扩展对齐说明符中的参数包。我无法正确使用语法。这是一个简单的例子:

#include <cstdint>
#include <tuple>

template <typename... Ts>
struct C
{
using Tuple_Type = std::tuple <Ts...>;

void f()
{
uint8_t i1;
uint8_t i2 alignas (2);
uint8_t i3 alignas (typename std::tuple_element<0, Tuple_Type>::type);
uint8_t i4 alignas (Ts...);
}
};

//template class C <>; // not compatible with i3 declaration above
template class C <uint64_t>;

使用 gcc 4.8.3 编译失败:

foo.cpp: In member function 'void C<Ts>::f()':
foo.cpp:14:31: error: expected ')' before '...' token
uint8_t i4 alignas (Ts...);
^
foo.cpp:14:31: error: expected ')' before '...' token
foo.cpp:14:31: error: expected initializer before '...' token

C++ 标准 ([dcl.align]) 说“带省略号的对齐说明符是包扩展”,所以看起来应该可以做我想做的事。

我一直无法找到这种参数包扩展的示例,而且我在 gcc 中搜索可能的错误也没有找到任何东西。

最佳答案

这看起来像 bug c++/59012在 GCC 中,已在 GCC 5.2 中修复。你的例子 compiles fine使用 Clang 3.5.1。

有趣的是,如果您完全省略省略号,GCC 会正确地提示参数包:

14 : error: parameter packs not expanded with '...':
uint8_t i4 alignas(Ts);
^

您将无法(轻松地)让它与 GCC 4.8.x 一起工作;这太愚蠢了。但是,对于 GCC 4.9 及更高版本,您可以使用以下我改编自 ecatmur's suggestion 的想法使用 constexpr max

template<int...>
struct maxInts {};

template<int A, int B, int... Cs>
struct maxInts<A, B, Cs...> {
const static int value = A > B ? maxInts<A, Cs...>::value : maxInts<B, Cs...>::value;
};

template<int A, int B>
struct maxInts<A, B> {
const static int value = A > B ? A : B;
};

template<int A>
struct maxInts<A> {
const static int value = A;
};

这只是让您在编译时获得任意数量整数中的最大值,如:

const int x = maxInts<1, 2, 3, 4, 5>::value; // x == 5

现在你麻烦的 alignas 看起来像这样:

uint8_t i4 alignas(maxInts<alignof(Ts)...>::value);

Here's a working example.

关于c++ - 使用 alignas 进行参数包扩展的语法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31812912/

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