简体   繁体   中英

Compile-time counter

Could you explain to me what is actually happening in my app? The outcome of my program is "0 1 1" when I expect "0 1 2" and so on...

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

What happens when I call GetMaxCounter<0>::max for the third time? Shouldn't template argument B be reevaluated to "true"?

Kind of a late answer, but the problem is due to the fact that you only have two "versions" of the class GetMaxCounter<N> ie GetMaxCounter<N, false> and GetMaxCounter<N, true> .

Essentially the max member is fixed to GetMaxCounter<0,false>::max (== 0) on the first call to GetMaxCounter<0>::max , when writer<1> is called, GetMaxCounter<0,true>::max is defined to be GetMaxCounter<1, false>::max (== 1).

Regardless of whether you called writer<2> or not, any subsequent GetMaxCounter<0> will be evaluated as GetMaxCounter<0, true> which has GetMaxCounter<0, true>::max previously defined as GetMaxCounter<1, false>::max and will not change.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM