按模板类型对齐成员变量

Lee*_*der 2 c++ templates

我想根据类模板类型对齐我的成员变量,但我不确定它是否真的可行.

以下是我想做的一个(非常)简单的例子

template<int Align>
class MyClass
{
private:
  struct MyStruct
  {
    // Some stuff
  } __declspec(align(Align));

  __declspec(align(Align)) int myAlignedVariable;
};
Run Code Online (Sandbox Code Playgroud)

所以我想要的是Align是一个每个实例的变量,只有这样才能确定类内容的对齐值.

不幸的是我总是得到以下错误

error C2975: 'test::MyClass' : invalid template argument for 'Align', expected compile-time constant expression
Run Code Online (Sandbox Code Playgroud)

那么,这实际上是可能的还是只能使用固定的编译时间常数进行对齐?如果没有,有人能想到解决这个问题的方法吗?

谢谢 :)

pmd*_*mdj 5

自定义对齐不在标准中,因此编译器如何处理它取决于它们 - 看起来VC++不喜欢将模板与__declspec组合.

我建议使用专门化的解决方法,如下所示:

template<int A> struct aligned;
template<> struct aligned<1> { } __declspec(align(1));
template<> struct aligned<2> { } __declspec(align(2));
template<> struct aligned<4> { } __declspec(align(4));
template<> struct aligned<8> { } __declspec(align(8));
template<> struct aligned<16> { } __declspec(align(16));
template<> struct aligned<32> { } __declspec(align(32));
Run Code Online (Sandbox Code Playgroud)

然后从你的代码中派生出来:

template<int Align>
class MyClass
{
private:
  struct MyStruct : aligned<Align> {
    // stuff
  };
};
Run Code Online (Sandbox Code Playgroud)

不幸的是,这打破了MyStruct的POD.它也不适用于内置/现有类型,因此您必须使用包装器.

aligned_t<int, 4> myAlignedVariable;
Run Code Online (Sandbox Code Playgroud)

  • 为什么不让他"调整"MyStruct的第一个成员?然后它仍然是pod. (2认同)