【问题标题】:Describe the memory consumption of this metaprogram描述这个元程序的内存消耗
【发布时间】:2023-03-29 15:11:01
【问题描述】:

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

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++ metaprogramming template-meta-programming


    【解决方案1】:

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

    当然,编译器必须以某种方式实例化所有模板特化并计算binary&lt;101010&gt;::value。但是编译完成后就不再重要了。

    【讨论】:

      【解决方案2】:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-03-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多