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

Asked

Viewed 90 times

5

#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

1 answer

6


Static data members need to initialize outside the class declaration. This is:

struct S {
    static int i;
};

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

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

With the qualifier const, the standardization allows initializing the static member with some constant expression (i.e., one can initialize with a literal like 42, but cannot initialize with some value that does not result in a constant expression).

In , it is possible to use the specifier inline to allow initialization of the data member at the same location as its declaration:

struct S {
    static inline int i = 42;
};

Here, the inline has the same effect when applied in functions: its initialization may appear on one or more translation units (as long as they are equivalent, e.g. included by a directive #include) and only one of them will actually be used.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.