模板中的 C++ 枚举 class 不能用作常量值

c++ enum inside template class can't be used as const value

这是代码,

#include<iostream>
using namespace std;

template <typename T>
class TestClass {
  T value;
  enum _SyncType {
    SYNC_TYPE,
    ASYNC_TYPE,
  };

  static const char *const kSyncString[];
};

template <typename T>
const char *const TestClass<T>::kSyncString[] = {
  [TestClass<T>::SYNC_TYPE]  = "sync type",
  [TestClass<T>::ASYNC_TYPE]  = "async type",
};

int main() {
  TestClass<int> test;
  return 0;
}

编译的时候提示

prog.cpp:19:1: error: the value of 'SYNC_TYPE' is not usable in a constant expression
 };
 ^
prog.cpp:8:5: note: 'TestClass<T>::_SyncType SYNC_TYPE' is not const
     SYNC_TYPE,
     ^
prog.cpp:19: confused by earlier errors, bailing out

我想可能模板还没有任何实例,但是我应该怎么写这样的代码?

const char *const TestClass<T>::kSyncString[] = {
  [TestClass<T>::SYNC_TYPE]  = "sync type",
  [TestClass<T>::ASYNC_TYPE]  = "async type",
};

这种初始化方式叫做designated initializer, which C99 has. Since C++11 doesn't have this feature,gcc有这个功能作为扩展。

我找到了it in the onlinedocs。它在“C 语言家族的 6 个扩展”中,而不是“C++ 语言的 7 个扩展”。所以,我猜 gcc 无法处理 C 扩展中的 C++ 功能(TestClass<T>::SYNC_TYPE - 模板和作用域运算符)。 (只是猜测>o<)无论如何,似乎可以肯定这是编译器扩展的失败。