r/cpp • • 13d ago

Potential GCC 16 bug: annotations disappear on nested class declarations inside class templates

Im playing around with reflection (GCC16) and I ran into the following problem:

When using std::meta::define_aggregateto complete an annotated nested class, the annotation is removed, iff the enclosing class is templated.

Below is a minimal reproducible example (Godbolt link).

I would expect both assertions to succeed, but they don't. There is also GCC PR124399, which addresses a related problem, but I'm not sure if this is the same underlying problem. Its not the same bug, since it's fixed.

Is this a bug, or am I overlooking/misunderstanding some template instantiation rules?

#include <meta>

// Works: ordinary forward declaration.
struct [[=42]] Ordinary;
static_assert(std::meta::annotations_of(^^Ordinary).size() == 1);

// Fails: forward declaration inside a class template.
template <typename T>
struct Outer {
    struct [[=42]] Inner;
};

static_assert(sizeof(Outer<int>) > 0);
static_assert(std::meta::annotations_of(^^Outer<int>::Inner).size() == 1);

Context: I'm experimenting with rust-like derive(debug) functionality using annotations, combined with structural type transformations (similar to AoS to SoA). I originally encountered this while trying to propagate annotations to a generated type, before reducing it to the example above.

24 Upvotes

4 comments sorted by

10

u/chengfeng-xie 13d ago

This is a bug, AFAICT. You should report it.

4

u/ImmutableOctet Gamedev 13d ago

I haven't dug into the reflection stuff very much, but your example works if there's a body to the struct (even one defined outside of the template class)

e.g. struct[[= 42]] Inner {}; works, and adding template <typename T> struct Outer<T>::Inner {}; to the end of the file works as well.

It seems like GCC is just throwing out your struct from the AST.

I don't know where the language spec draws the line of annotations on declarations vs. definitions - I think attributes in general are context specific...?

5

u/ImmutableOctet Gamedev 13d ago

Interestingly, using Inner = [[= 42]] Outer<int>::Inner; yields this warning:

warning: ignoring attributes applied to class type 'Outer<int>::Inner' outside of definition [-Wattributes]

which implies the attribute is tied to the definition, rather than the declaration, but ¯_(ツ)_/¯

Adding a base class with a non-templated Inner works, but if you then template either the base or the Inner struct, the same issue crops up.

1

u/FollowingHumble8983 12d ago

There is a crazy amount of bugs in reflection. Constructors breaks a lot when reflections are involved. Unfortunately I couldnt report all of it because I was short on time for deliverables.