Home > Net >  Why do I need the extra pair of curly braces when defining an array of pairs?
Why do I need the extra pair of curly braces when defining an array of pairs?

Time:10-22

I'm sorry if this is a common question, I don't know how I'd search for it so I figured it best to just ask.

I'm wanting to define an std::array of std::pairs in C to store SFML sf::IntRects in. I messed with it for like 10 minutes and finally realized that this compiles:

std::array<std::pair<sf::IntRect, sf::IntRect>, 1> aliens{
    {
        {sf::IntRect{2,3,1,2}, sf::IntRect{4,1,3,2}}
    }
};

Why do I need the extra set of curly braces around the pair itself? When I take them away:

std::array<std::pair<sf::IntRect, sf::IntRect>, 1> aliens{
    {sf::IntRect{2,3,1,2}, sf::IntRect{4,1,3,2}}
};

I get an error No suitable user-defined conversion from "sf::IntRect" to "std::pair<sf::IntRect,sf::IntRect>" exists

What are these curly braces doing? I can't imagine what they'd be needed for.

CodePudding user response:

std::array is a wrapper template around built-in C-style array. You may think of it as something like

template <typename T, std::size_t N>
class array {
  T arr[N];
  ...
};

Both std::array and built-in C-style array are aggregate types. You initialize it using aggregate initialization syntax. It would be something like

std::array<T, N> array = {{ t0, t1, t2 }};

The outer {} is for std::array itself while the inner {} is for the wrapped built-in C-style array.

Look at your example

std::array<std::pair<sf::IntRect, sf::IntRect>, 1> aliens{
    {sf::IntRect{2,3,1,2}, sf::IntRect{4,1,3,2}}
};

The error is more obvious when reformated as below.

std::array<std::pair<sf::IntRect, sf::IntRect>, 1> aliens{{
  sf::IntRect{2,3,1,2},
  sf::IntRect{4,1,3,2}
}};

You are trying to initialize a pair with a single sf::IntRect object.

  • Related