[英]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? 我的问题是 - 分配value
的内存在哪里? 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? 这是否意味着每个模板实例化,在数据段上分配新的unsigned
?
value
has no definition. value
没有定义。 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;
它们的值将被内联,就好像你unsigned x = 42;
. 。
Of course the compiler has to somehow instantiate all the template specializations and calculate binary<101010>::value
. 当然, 编译器必须以某种方式实例化所有模板特化并计算binary<101010>::value
。 But that doesn't matter anymore after compilation is complete. 但是编译完成后再也没关系了。
If you use a good C++ compiler, no memory gets allocated anywhere. 如果你使用一个好的C ++编译器,任何地方都不会分配任何内存。 The C++ compiler will completely optimize away this class, and use the calculated constant directly, in whatever code uses it. C ++编译器将完全优化掉这个类,并在任何使用它的代码中直接使用计算出的常量。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.