[英]Assign static const float member of a template class according to template arguments
I have a template class : 我有一个模板类:
template<int A, int B>
struct MyStruct
{
enum
{
a = A,
b = B
};
static const float c;
};
I would like to define c as a function of a and b. 我想将c定义为a和b的函数。 Like this :
像这样 :
//Hypotetic, doesn't compile since MyStruct isn't specialized.
const float MyStruct::c = MyStruct::a / static_cast<float>(MyStruct::b);
I already have an other solution for the "real" code. 我已经有了针对“真实”代码的其他解决方案。 I was just curious.
我只是好奇而已。 How would you do it ?
你会怎么做?
in c++11 you simply initialize the constant inline as in: 在c ++ 11中,您只需按以下方式初始化常量内联:
static constexpr float c = (a + b + 5.);
in c++98 you leave the struct as it is, then you declare the static variable as in: 在c ++ 98中,将结构保持原样,然后在以下位置声明静态变量:
template<int A, int B>
const float MyStruct<A, B>::c = A + B + 5.;
or 要么
template<int A, int B>
const float MyStruct<A, B>::c = MyStruct<A, B>::a + MyStruct<A, B>::b + 5.;
whichever makes more sense. 以更合理的方式。
Note that you can even specialize the value for c
. 注意,您甚至可以将
c
的值专用化。 In your example, if B is zero you would be dividing by 0. A possible solution is: 在您的示例中,如果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;
which is a bit cumbersome, yet is the only way of specialising the static member variable. 这有点麻烦,但却是专用于静态成员变量的唯一方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.