Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Describe the memory consumption of this metaprogram

I found this working code in a book on Metaprogramming -

template<unsigned long N>
struct binary
{
    static unsigned const value = binary<N/10>::value *2 + N%10;    
};

template<>
struct binary<0>
{
    static unsigned const value = 0;
};

int main()
{
    unsigned x = binary<101010>::value;
    cout << x;
}

My question is - where is the memory for value allocated? Is it allocated on the data segment?

Also, the book says that this code results in a cascade of template instantiations which computes the result in a manner similar to recursion. Does that mean for each template instantiation, a new unsigned is allocated on the data segment?

like image 445
The Vivandiere Avatar asked Jan 07 '23 04:01

The Vivandiere


1 Answers

value has no definition. Such static data members can only be used in ways that don't require them to have an address (they cannot be odr-used). Their values will be inlined, as though you had unsigned x = 42;.

Of course the compiler has to somehow instantiate all the template specializations and calculate binary<101010>::value. But that doesn't matter anymore after compilation is complete.

like image 80
Brian Bi Avatar answered Jan 14 '23 14:01

Brian Bi