我在解决 GCC 问题时遇到问题。我在 GCC 4.8 下体验过它,但不是 5.1。看起来它被报道了here和/或 here .
问题如下:
template <bool B>
struct S
{
static const int ALIGN = 16;
__attribute__((aligned(ALIGN))) int x;
};
int main(int argc, char* argv[])
{
S<true> s1;
S<false> s2;
return 0;
}
和:
$ g++ test.cxx -o test.exe
test.cxx:9:41: error: requested alignment is not an integer constant
__attribute__((aligned(ALIGN))) int x;
我保留 static const
也很重要,因为 Clang 的优化不如 GCC。 C++03 也是一项要求。
这是一个相关的问题,但它只是指出了错误,并没有提供解决方法:Using constant from template base class .
我该怎么做才能解决这个问题?
这是问题编译器,但可能还有其他人考虑到其中一个问题已经存在了 3 年左右。
$ g++ --version
g++ (Ubuntu 4.8.4-2ubuntu1~14.04.1) 4.8.4
Copyright (C) 2013 Free Software Foundation, Inc.
实际用例要复杂一些。如果机器提供 SSE2 或更高版本,则对齐为 16。如果机器提供 SSE4 或更高版本,则对齐为 32。否则,我们将退回到自然对齐。所以它更接近于:
template <class W, bool B, unsigned int S>
struct X
{
static const int ALIGN = (B ? 16 : sizeof(W));
__attribute__((aligned(ALIGN))) W x[S];
};
int main(int argc, char* argv[])
{
X<int, true, 10> x1;
X<long, false, 20> x2;
return 0;
}
最佳答案
正如您所说的,C++03 支持是一项要求,我会回到(是的 C-ish...)良好的旧定义:
template <bool B>
struct S
{
#define CONST_ALIGN 16
static const int ALIGN = CONST_ALIGN; // to allow using it later as S<B>.ALIGN
__attribute__((aligned(CONST_ALIGN))) int x; // this uses a litteral int constant
};
当然,定义不是结构的本地定义,并且可以在以下所有行中访问。但毕竟它不会造成太大伤害 (*) 并且允许老编译器理解这一点而无需重复魔法乱码(此处为 16)。
(*) 如果您稍后在同一个文件中使用 near 声明,它只能隐藏可能的拼写错误:
static const int CONST_ALIGNER = 12;
...
int b = CONST_ALIGN; // TYPO should have been CONST_ALIGNER
这会导致难以发现错误
关于c++ - 错误 "requested alignment is not an integer constant",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36642315/