【问题标题】:Initialize a static const member with a template argument使用模板参数初始化静态 const 成员
【发布时间】:2017-03-29 12:50:58
【问题描述】:

我有几行在我的系统上编译得很好,但在同事系统上却没有编译。这就是为什么我想问一下这个问题的首选解决方案是什么样的。我必须处理一个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 的最可靠方法是什么。

【问题讨论】:

  • clang 编译器有多老?他们支持 C++11? (枚举类和std::array 是 C++11 引入的特性)。并且,请您转录确切的错误吗?
  • LLVM 5.1,所以它是 XCode 5.1.1。我们使用 C++11,这有点奇怪。 (抱怨这个的编译器不会支持 c++11)错误:in-class initializer for static data member is not a constant expression

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


【解决方案1】:

您的代码对我来说似乎是正确的,并且可以使用我的旧 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;
};

【讨论】:

    猜你喜欢
    • 2012-02-02
    • 2011-03-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-13
    • 1970-01-01
    • 2020-10-07
    相关资源
    最近更新 更多