c++ - 有状态的元编程是病态的(还)吗?

标签 c++ language-lawyer metaprogramming c++17

我有幸遇到的最心爱/邪恶的发明之一是 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/52557830/

相关文章:

c++ - 使用 enable_if 选择性地添加结构成员

C++ Boost::MPL fold 示例 - 参数数量错误

c++ 代码折叠与 emacs/cedet

c++ - 是否可以使用有条件选择的字符串文字来初始化字符数组?

c++ - 为什么 c 和 c++ 对待未初始化变量的重新定义不同?

c++ - 如果 voidPtr 是空指针或指向从 Base 继承的对象,dynamic_cast<Derived*>(static_cast<Base*>(voidPtr)) 会出错吗?

c++ - 如何使用 Variadic 模板来展平类型树?

c++ - 在 C++ 中读取整数并打印新行直到文件末尾

c++ - C++Builder6 中的 Random_shuffle 替代方案

c++ - FFMPEG I/O 输出缓冲区