Home > Blockchain >  c standard_layout for ref types
c standard_layout for ref types

Time:03-31

I'm trying to understand why standard_layout does not apply to ref types?

#include <type_traits>

struct X {
    int y;
};

static_assert(std::is_standard_layout_v<X>);
static_assert(std::is_standard_layout_v<X&>); // does not compile

CodePudding user response:

As you've found, is_standard_layout only works with an object type, not a reference.

As such, if you want either a type or a reference to a type, you could use:

static_assert(std::is_standard_layout_v<std::remove_reference_t<X>>);

remove_reference_t will yield the referred-to type for a reference, or the type itself if what you pass isn't a reference (note: for older compilers, you can use std::remove_reference<T>::type).

CodePudding user response:

Because a standard layout type is defined by the standard in from [basic.types]:

  • Scalar types
  • standard-layout class types
  • arrays of such types and
  • cv-qualified versions of these types

are collectively called standard-layout types.

The list of things that constitute a standard-layout class type is rather long (cf. [class]) but a reference is obviously not a class.

In particular that list says nothing about references, so a reference to even a standard-layout type (like int or float const[16]) is not standard-layout itself.

  • Related