根据模板参数分配模板类的静态常量浮点成员

Assign static const float member of a template class according to template arguments

本文关键字:常量 静态 成员 参数 分配      更新时间:2023-10-16

我有一个模板类:

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;

这有点麻烦,但却是专门化静态成员变量的唯一方法。