有状态的元编程格式不正确吗? [英] Is stateful metaprogramming ill-formed (yet)?

查看:84
本文介绍了有状态的元编程格式不正确吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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 :

在模板中定义一个朋友函数,然后在以后引用该函数提供了一种捕获和检索元编程状态的方法.该技术是不可思议的,应使其变形.

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.

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.

这篇关于有状态的元编程格式不正确吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆