使用模板参数初始化静态常量成员 [英] Initialize a static const member with a template argument
问题描述
我有几行可以在我的系统上很好地编译,但不能在同事系统上编译.这就是为什么我想问这个问题的首选解决方案是什么样的.我必须处理一个 enum
,它隐含地定义了我必须为 std::array
提供多少空间.代码的其他部分也使用 FooSize
是静态的.(优化)
I have a few lines that compile well on my system but don't compile on a colleagues system. That's why I would like to ask what the go-to solution for the problem would look like. I have to deal with a enum
that implicitly defines how much space I have to provide for an std::array
. Other parts of the code also make use of FooSize
being static. (Optimization)
我目前的实现是这样的
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 编译器上产生了问题.32
和 64
实际上是通过预处理器定义提供的.我可以跳过 FooType
并将大小用作模板参数,但我想知道初始化 FooSize
的最可靠方法是什么.
The code seems to create issues on older llvm / clang compilers. 32
and 64
are actually provided via pre processor defines. I could just skip the FooType
and use the size as an template argument but I would like to know what the most reliable method of initializing FooSize
would be.
推荐答案
您的代码对我来说似乎是正确的,并且在使用我的旧版 g++ (4.9.2) 和 clang++ (3.5) 时编译没有问题.
Your code seems correct to me and compile without problems with my olds g++ (4.9.2) and clang++ (3.5).
但是,根据错误消息,可能是您的编译器没有正确支持静态数据成员的 C++11 声明/初始化
But, according the error message, could be that your compiler doesn't correctly support the C++11 declaration/initialization of static data members
建议您按以下方式尝试
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
.
You can also try defining FooSize
as constexpr
instead of const
.
另一种解决方案可能是在模板参数中转换 FooSize
Another solution could be transform FooSize
in a template parameter
template <FooType FType,
std::size_t FooSize = (FType == FooType::ShortFoo) ? 32 : 64 >
class FooContainer
{
public:
std::array<float, FooSize> fooArray;
};
这篇关于使用模板参数初始化静态常量成员的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!