简体   繁体   中英

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. 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:

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:

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 . In your example, if B is zero you would be dividing by 0. A possible solution is:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM