Is stateful metaprogramming ill-formed (yet)?

C++Language LawyerMetaprogrammingC++17

C++ Problem Overview


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?

The following is an implementation largely based on the post

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

And we use it as

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

This by the way, is a direct contradiction to https://stackoverflow.com/questions/6105994/storing-states-in-c-metaprogramming

C++ Solutions


Solution 1 - C++

This is 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.

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionPasser ByView Question on Stackoverflow
Solution 1 - C++BarryView Answer on Stackoverflow