Unnamed struct
is allowed (type has no name)
void foo()
{
struct /* No name */ {
float x;
float y;
} point;
point.x = 42;
}
or
struct Circle
{
struct /* No name */ {
float x;
float y;
} center; // but a member name
float radius;
};
and later
Circle circle;
circle.center.x = 42.f;
but NOT anonymous struct
(unnamed type and unnamed object)
struct InvalidCircle
{
struct /* No name */ {
float centerX;
float centerY;
}; // No member either.
float radius;
};
Note: Some compilers allow anonymous struct
as extension.
lamdba can be seen as a special unnamed struct
.
decltype
allows to retrieve the type of unnamed struct
:
decltype(circle.point) otherPoint;
unnamed struct
instance can be parameter of template method:
void print_square_coordinates()
{
const struct {float x; float y;} points[] = {
{-1, -1}, {-1, 1}, {1, -1}, {1, 1}
};
// for range relies on `template <class T, std::size_t N> std::begin(T (&)[N])`
for (const auto& point : points) {
std::cout << "{" << point.x << ", " << point.y << "}\n";
}
decltype(points[0]) topRightCorner{1, 1};
auto it = std::find(points, points + 4, topRightCorner);
std::cout << "top right corner is the "
<< 1 + std::distance(points, it) << "th\n";
}