How to check whether T is an aggregate type?
Asked Answered
T

1

7

I know about std::is_pod. But it checks more than just aggregate types. Or, is std::is_pod just the best we can do?

Basically, I want to write a function template for this:

template <typename T>
aggregate_wrapper<T> wrap(T&& x);

which is only enabled when T is an aggregate type.

Timothea answered 25/1, 2016 at 13:56 Comment(6)
I can't think of any practical application of an is_aggregate. E.g. it doesn't help with serialization.Preface
If you're looking for the type trait that tells you when e.g. memcpy is safe, then you want std::is_trivially_copyable.Morin
@Cheersandhth.-Alf I want to write a wrap() function template for this, which is only enabled if T is an aggregate type.Timothea
Do std::is_object or std::is_compound not meet your needs?Damnation
@Damnation No. It's about initialization syntax. Aggregate types support {}, but not ().Timothea
C++17 provides std::is_aggregate.Elyn
W
4

There is no way to synthesize an is_aggregate template. The rules for whether something participates in aggregate initialization cannot be detected by C++14 metaprogramming techniques (they would require reflection support).

The general reason for not having this is the lack of an explicit need. Even in the case of your wrapper, there's little harm in applying it to non-aggregate types, since uniform initialization syntax can be applied to non-aggregates. You'll make all conversions non-explicit, but that's something which can be fixed via clever metaprogramming/enable_if gymnastics.

The most useful place for such a thing would be in allocator::construct, which would allow you to use aggregate initialization to construct the object if T were an aggregate, while using direct constructor calls otherwise (to dodge the "not uniform" part of uniform initialization).

Willamina answered 25/1, 2016 at 14:35 Comment(1)
After a second thought, writing a wrap() like this may not be a good idea. Given an aggregate, you can't really tell whether the user wants to make an aggregate_wrapper or something else with just wrap(x) .Timothea

© 2022 - 2024 — McMap. All rights reserved.