【问题标题】:Compile-time counter编译时计数器
【发布时间】:2019-01-13 23:24:23
【问题描述】:

您能否向我解释一下我的应用中实际发生了什么?当我期望“0 1 2”等时,我的程序的结果是“0 1 1”……

#include <iostream>

template<int N>
struct counter {
    friend constexpr int get(counter<N>);
};

template<int N>
struct writer {
    friend constexpr int get(counter<N>) {
        return N;
    }
};

template<int N, bool B = noexcept(get(counter<N + 1>()))>
struct GetMaxCounter
{
    static constexpr int max = GetMaxCounter<N + 1>::max;
};

template<int N>
struct GetMaxCounter<N, false>
{
    static constexpr int max = N;
};

int main()
{
    std::cout << GetMaxCounter<0>::max << std::endl;
    writer<1>();
    std::cout << GetMaxCounter<0>::max << std::endl;
    writer<2>();
    std::cout << GetMaxCounter<0>::max << std::endl;
}

当我第三次调用 GetMaxCounter::max 时会发生什么?不应该将模板参数 B 重新评估为“真”吗?

【问题讨论】:

标签: c++ metaprogramming template-meta-programming


【解决方案1】:

有点晚的答案,但问题是由于您只有 GetMaxCounter&lt;N&gt; 类的两个“版本”,即 GetMaxCounter&lt;N, false&gt;GetMaxCounter&lt;N, true&gt;

基本上max 成员在第一次调用GetMaxCounter&lt;0&gt;::max 时被固定为GetMaxCounter&lt;0,false&gt;::max (== 0),当调用writer&lt;1&gt; 时,GetMaxCounter&lt;0,true&gt;::max 被定义为GetMaxCounter&lt;1, false&gt;::max (== 1 )。

无论您是否调用了writer&lt;2&gt;,任何后续的GetMaxCounter&lt;0&gt; 都将被评估为GetMaxCounter&lt;0, true&gt;,其中GetMaxCounter&lt;0, true&gt;::max 之前定义为GetMaxCounter&lt;1, false&gt;::max,并且不会更改。

【讨论】:

    猜你喜欢
    • 2016-11-26
    • 2015-01-14
    • 1970-01-01
    • 2015-10-21
    • 2011-09-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多