gpt4 book ai didi

c++ - 有状态的元编程格式不正确吗(还)?

转载 作者:IT老高 更新时间:2023-10-28 12:30:13 25 4
gpt4 key购买 nike

我有幸遇到的最心爱/最邪恶的发明之一是constexpr counter ,又名有状态的元编程。正如帖子中提到的,它似乎在 C++14 下是合法的,我想知道 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;
}

我们use it作为

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");

顺便说一句,这与 Storing States in C++ Metaprogramming? 直接矛盾。

最佳答案

这是CWG active issue 2118 :

Defining a friend function in a template, then referencing that function later provides a means of capturing and retrieving metaprogramming state. This technique is arcane and should be made ill-formed.

Notes from the May, 2015 meeting:

CWG agreed that such techniques should be ill-formed, although the mechanism for prohibiting them is as yet undetermined.

这仍然是一个活跃的问题,至少目前在 C++17 中不会有任何改变。虽然当这种禁止机制确定后,这可能会被追溯为 DR。

关于c++ - 有状态的元编程格式不正确吗(还)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44267673/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com