根据模板参数分配模板类的静态常量浮点成员
Assign static const float member of a template class according to template arguments
我有一个模板类:
template<int A, int B>
struct MyStruct
{
enum
{
a = A,
b = B
};
static const float c;
};
我想将 c 定义为 a 和 b 的函数。喜欢这个:
//Hypotetic, doesn't compile since MyStruct isn't specialized.
const float MyStruct::c = MyStruct::a / static_cast<float>(MyStruct::b);
我已经为"真实"代码提供了其他解决方案。我只是好奇。你会怎么做?
在
C++11 中,您只需内联初始化常量,如下所示:
static constexpr float c = (a + b + 5.);
在 C++98 中,您将结构保持原样,然后将静态变量声明为 in:
template<int A, int B>
const float MyStruct<A, B>::c = A + B + 5.;
或
template<int A, int B>
const float MyStruct<A, B>::c = MyStruct<A, B>::a + MyStruct<A, B>::b + 5.;
以更有意义的为准。
请注意,您甚至可以专门化c
的值。在您的示例中,如果 B 为零,则将除以 0。一个可能的解决方案是:
template<int A>
struct MyStruct<A, 0>
{
enum
{
a = A,
b = 0
};
static const float c;
};
template<int A>
const float MyStruct<A, 0>::c = A;
这有点麻烦,但却是专门化静态成员变量的唯一方法。
相关文章:
- 常量静态成员函数
- 常量静态成员函数:有另一种方法可用吗?
- C++常量静态字符* 数组
- 为什么常量静态变量应该在结构中初始化?
- 使用 constexpr 初始化非常量静态字符串
- 初始化常量静态 std::map unique_ptr作为值
- 静态函数常量静态成员函数
- 不能将值 120 分配给静态常量无符号字符或将值 200 分配给常量静态无符号 int
- 静态常量与常量静态
- 声明"静态常量"和"常量静态"有什么区别
- 常量静态成员初始化 - 类定义内部与外部类定义
- 为什么一个非常量静态成员会有多个定义
- 在类内部使用常量-静态与非静态
- 模板/泛型类中的非常量静态成员- c++与c#
- 类中的常量静态函数指针~如何初始化它
- 无法访问常量静态标准::映射枚举结构
- C++初始化非常量静态成员变量
- When是一个非静态常量数据成员,比常量静态成员更有用
- C++11 MinGW 4.9.1 shared_ptr和常量静态类字段结果"Undefined reference"
- c++动态初始化常量静态向量