描述这个元程序的内存消耗

Describe the memory consumption of this metaprogram

我在一本关于元编程的书中找到了这个工作代码 -

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;
}

我的问题是 - value 的内存分配在哪里?是否分配在数据段上?

另外,书中说这段代码会产生一系列模板实例化,这些实例化以类似于递归的方式计算结果。这是否意味着对于每个模板实例化,都会在数据段上分配一个新的 unsigned

如果您使用良好的 C++ 编译器,则不会在任何地方分配内存。 C++ 编译器将完全优化掉这个 class,并在任何使用它的代码中直接使用计算出的常量。

value 没有定义。此类静态数据成员只能以不需要它们具有地址的方式使用(它们不能 odr-used)。它们的值将被内联,就像您有 unsigned x = 42;.

当然,编译器 必须以某种方式实例化所有模板特化并计算 binary<101010>::value。不过编译完成后就无所谓了