Home > Backend Development > C++ > body text

Stateful Metaprogramming in C : A Legal Technique in C 14, But Will That Change in C 17?

DDD
Release: 2024-11-20 18:52:16
Original
801 people have browsed it

Stateful Metaprogramming in C  : A Legal Technique in C  14, But Will That Change in C  17?

Stateful Metaprogramming: Is It Still Legal in C

One of the more controversial metaprogramming techniques in C , stateful metaprogramming, relies on the concept of constexpr counter to store and retrieve metaprogramming state. As it stands, this technique is legal under C 14. However, this raises the question of whether this will change with the introduction of C 17.

To understand the issue at hand, consider the following implementation based on a previous post:

// State storage flag
template <int N>
struct flag {
    friend constexpr int adl_flag(flag<N>&);
    constexpr operator int() { return N; }
};

// State writer
template <int N>
struct write {
    friend constexpr int adl_flag(flag<N>) { return N; }
    static constexpr int value = N;
};

// State reader
template <int N, int = adl_flag(flag<N>{})>
constexpr int read(int, flag<N>, int R = read(0, flag<N + 1>{})) {
    return R;
}

// Stateful counter
template <int N = 0>
constexpr int counter(int R = write<read(0, flag<0>{}) + N>::value) {
    return R;
}
Copy after login

This technique is employed as follows:

// Check if counter is stateful with static assertion
static_assert(counter() != counter(), "Your compiler is mad at you");

// Template specialization based on counter state
template<int = counter()>
struct S {};

// Check if template specializations differ with static assertion
static_assert(!std::is_same_v<S<>, S<>, "This is ridiculous");
Copy after login

However, the legality of stateful metaprogramming came into question with CWG Active Issue 2118. The issue proposes that using friend functions in templates to capture and retrieve metaprogramming state should be deemed ill-formed due to its arcane nature.

As of May 2015, CWG agreed that such techniques should be prohibited but has yet to determine a proper mechanism. The issue remains active, and until a decision is made, stateful metaprogramming will remain legal in C . However, when a prohibition mechanism is established, this technique may be retroactively declared as a defect report.

The above is the detailed content of Stateful Metaprogramming in C : A Legal Technique in C 14, But Will That Change in C 17?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template