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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With