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

The*_*ere 4 c++ metaprogramming template-meta-programming

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

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;
}
Run Code Online (Sandbox Code Playgroud)

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

此外,该书还说这段代码导致了一系列模板实例化,它们以类似于递归的方式计算结果.这是否意味着每个模板实例化,unsigned在数据段上分配一个新的?

Bri*_*ian 6

value没有定义.这样的静态数据成员只能以不要求它们具有地址的方式使用(它们不能被使用).他们的价值观将被内联,就好像你有unsigned x = 42;.

当然,编译器必须以某种方式实例化所有模板特化并进行计算binary<101010>::value.但是编译完成后再也没关系了.