C++ Logo

std-proposals

Advanced search

Re: [std-proposals] Tagging

From: Matthias Wippich <mfwippich_at_[hidden]>
Date: Sun, 20 Apr 2025 02:44:56 +0200
I do not see the need for a language feature for this. Note that with the
reflection features proposed in P2996 (https://wg21.link/p2996) and
annotation attributes from P3394 (https://wg21.link/p3394) this can also be
trivially done reflectively.

Consider a metafunction
```
template <typename T>
consteval bool has_tag(std::meta::info type, T, bool include_bases = true) {
    auto is_tagged = [](auto r) {
        return !annotations_of(is_type(r) ? r : type_of(r), ^^T).empty();
    };

    if (is_tagged(type)) {
        return true;
    } else if (include_bases) {
        return std::ranges::any_of(bases_of(type), is_tagged);
    }
    return false;
}
```

This metafunction matches annotations by type, so you need to introduce a
new type for every tag, ie by saying
```
struct {} constexpr inline some_tag {};
```

Which in turn allows you to actually tag types and check for the presence
of the tag (possibly including bases)
```
struct[[= some_tag]] Base {};
struct Derived : Base {};

static_assert(has_tag(^^Base, some_tag));
static_assert(has_tag(^^Derived, some_tag));
static_assert(not has_tag(^^Derived, some_tag, false));
```

Full example: https://cpp26.godbolt.org/z/96cEoe9vh

Received on 2025-04-20 00:45:22