[英]Compile-time counter
你能向我解釋一下我的應用程序中實際發生了什么嗎? 當我期望“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<0>::max 時會發生什么? 模板參數 B 不應該重新評估為“真”嗎?
有點晚的答案,但問題是由於您只有GetMaxCounter<N>
類的兩個“版本”,即GetMaxCounter<N, false>
和GetMaxCounter<N, true>
。
本質上,在第一次調用GetMaxCounter<0>::max
時, max
成員固定為GetMaxCounter<0,false>::max
(== 0),當調用writer<1>
, GetMaxCounter<0,true>::max
定義為GetMaxCounter<1, false>::max
(== 1)。
無論您是否調用了writer<2>
,任何后續的GetMaxCounter<0>
都將被評估為GetMaxCounter<0, true>
,其中GetMaxCounter<0, true>::max
先前定義為GetMaxCounter<1, false>::max
並且不會改變。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.