【发布时间】: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 重新评估为“真”吗?
【问题讨论】:
-
I've been there too. 有人告诉我,由于
[temp.res]/8.5,有状态模板元编程在 C++17 中已被废除(链接的问题称为8.4,此后编号已更改),据称这使代码格式错误,NDR。但我承认我不确定该部分在这里的具体应用情况。 -
我什至不知道第三段中的
get指的是什么。不过我想分享这个:boostorg.github.io/hana/index.html#tutorial-integral
标签: c++ metaprogramming template-meta-programming