问题描述
constexpr counter ,又称为有状态的元编程.正如文章中提到的,在C ++ 14下似乎是合法的,我想知道C ++ 17有什么变化吗?
One of my most beloved/evil inventions I've had the fortune to come across is the constexpr counter, aka stateful metaprogramming. As mentioned in the post, it seems to be legal under C++14, and I'm wondering has anything changed with C++17?
以下是基于帖子的实现
template <int N>
struct flag
{
friend constexpr int adl_flag(flag<N>);
constexpr operator int() { return N; }
};
template <int N>
struct write
{
friend constexpr int adl_flag(flag<N>) { return N; }
static constexpr int value = N;
};
template <int N, int = adl_flag(flag<N>{})>
constexpr int read(int, flag<N>, int R = read(0, flag<N + 1>{}))
{
return R;
}
template <int N>
constexpr int read(float, flag<N>)
{
return N;
}
template <int N = 0>
constexpr int counter(int R = write<read(0, flag<0>{}) + N>::value)
{
return R;
}
我们使用它为
static_assert(counter() != counter(), "Your compiler is mad at you");
template<int = counter()>
struct S {};
static_assert(!std::is_same_v<S<>, S<>>, "This is ridiculous");
顺便说一下,这与在C ++元编程中存储状态有直接矛盾吗?
推荐答案
这是 CWG活动问题2118 :
2015年5月会议上的笔记:
CWG同意,尽管尚未确定禁止这种技术的机制,但这些技术应采用错误的形式.
CWG agreed that such techniques should be ill-formed, although the mechanism for prohibiting them is as yet undetermined.
这仍然是一个活跃的问题,至少在目前,C ++ 17不会有任何改变.尽管在确定了这样的禁止机制后,可以将其追溯为DR.
It's still an active issue, nothing will change in C++17 at least for now. Though when such a prohibition mechanism is determined, this may be retroactively ruled as a DR.
这篇关于有状态的元编程格式不正确吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!