Using template, why use const modifier in this variable (C ++)?

4
#include <iostream>
using std::cout;
using std::endl;

template <unsigned int i> 
struct Fibo{
    static const unsigned result = Fibo<i-1>::result + Fibo<i-2>::result;
};

template <>
struct Fibo<0>{
    static const unsigned result = 1;
};

template <>
struct Fibo<1>{
    static const unsigned result = 1;
};

int main () {
    cout << Fibo<5>::result << endl;

    return 0;
}

If the const modifier is removed, the compiler declares

  

error: non-const static data member must be initialized out of line

    
asked by anonymous 27.12.2018 / 20:51

1 answer

5

Static data members need an initialization outside the class declaration. This is:

struct S {
    static int i;
};

int S::i = 42; // definição

This is a language restriction, following the rule of a definition (one definition rule, or ODR). The constraint exists to prevent two or more initializations from occurring for the S::i static member (for example, if the class is included in two distinct translation units). Note: The initialization needs to appear only in a translation unit, otherwise the behavior is undefined.

With the qualifier const , standardization allows you to initialize the static member with some constant expression (that is, it can be initialized with a literal like 42 , but can not initialize with some value that does not result in an expression constant).

In , you can use the inline specifier to allow the initialization of the data member in the same location as your declaration:

struct S {
    static inline int i = 42;
};
Here, inline has the same effect when applied to functions: its initialization can appear in one or more translation units (as long as they are equivalent, eg included by a #include directive), and only one of them will be used in fact.

    
27.12.2018 / 22:06