c++ - 使用模板参数初始化静态常量成员

标签 c++ c++11 templates static-members static-initialization

我有几行代码在我的系统上编译得很好,但在同事的系统上却编译不了。这就是为什么我想问问这个问题的首选解决方案是什么样的。我必须处理一个 enum,它隐式定义了我必须为 std::array 提供多少空间。代码的其他部分也使用静态的 FooSize。 (优化)

我目前的实现是这样的

enum class FooType
{
    ShortFoo,
    LongFoo
};

// defined in a different file
template <FooType FType>
class FooContainer
{
public:

    static const unsigned int FooSize {(FType == FooType::ShortFoo) ? 32 : 64 };

    std::array<float, FooSize> fooArray;

};

该代码似乎会在较旧的 llvm/clang 编译器上产生问题。 3264 实际上是通过预处理器定义提供的。我可以跳过 FooType 并将大小用作模板参数,但我想知道初始化 FooSize 的最可靠方法是什么。

最佳答案

你的代码对我来说似乎是正确的,并且在我的旧 g++ (4.9.2) 和 clang++ (3.5) 上编译没有问题。

但是,根据错误信息,可能是您的编译器没有正确支持静态数据成员的 C++11 声明/初始化

我建议你用下面的方法试试

template <FooType FType>
class FooContainer
{
public:
    static const unsigned int FooSize;

    std::array<float, FooSize> fooArray;

};

template <FooType FType>
int unsigned const FooContainer<FType>::FooSize
   = ((FType == FooType::ShortFoo) ? 32 : 64);

或者(我想更好)

template <FooType FType>
class FooContainer
{
public:

    static const unsigned int FooSize {(FType == FooType::ShortFoo) ? 32 : 64 };

    std::array<float, FooSize> fooArray;

};

template <FooType FType>
int unsigned const FooContainer<FType>::FooSize;

您也可以尝试将 FooSize 定义为 constexpr 而不是 const

另一种解决方案是在模板参数中转换 FooSize

template <FooType FType,
   std::size_t FooSize = (FType == FooType::ShortFoo) ? 32 : 64 >
class FooContainer
{
public:
    std::array<float, FooSize> fooArray;
};

关于c++ - 使用模板参数初始化静态常量成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43094045/

相关文章:

c++ - 从 C++ 调用 C 程序并传递参数

c++ - 在 Windows 上,命名管道文件存储在哪里?

C++11 无法移动内部有 unordered_map 的类

c++ - 如果我返回文字而不是声明的 std::string 会怎样?

c++ - 编译器选择专门用于数组的预期模板,但随后尝试将数组参数转换为指针

templates - 模板函数重载推导错误

c++ - Unix 程序控制台与其他东西

c++ - OpenCL 中的 memset 局部变量/内存

c++ - 在 ImGui 中嵌入大于字符大小的字体

C++ 数组下标运算符模板