0

I have a global static std::vector<Type>, and a struct which will hopefully select from one of the elements.

typedef struct
{
    bool initial
    bool opening;
    std::string friendly_name;
} Type;

using TypeVec = std::vector<Type>;
static const TypeVec starting_types
{
    { true, true, "Open" },
    { true, false, "Close" },
    ...
};

typedef struct
{
    Type type;
} SessionInfo;

Now the SessionInfo struct will choose one of the types in the starting_types. If I write

SessionInfo session;
session->type = starting_types.at (0);

This will create a copy of the first element. I want to do the equivalent of auto& thus:

auto& type = starting_types.at (0);

But don't know how to save it into SessionInfo::type.

wohlstad
  • 12,661
  • 10
  • 26
  • 39
Chris Lam
  • 33
  • 5
  • 5
    Make `Type type;` in `SessionInfo` a reference or a pointer, otherwise it will always be a copy. Also there's no need to do `typedef struct {...} Name;` in C++, just write `struct Name {...};`. – HolyBlackCat Feb 10 '22 at 07:19
  • 1
    Not related to your question, but `starting_types` being `const` indicates, that the number of elements stored in `starting_types` is known at compile time. So you probably want to use `std::array` instead. You might also want to look at [Difference between 'struct' and 'typedef struct' in C++?](https://stackoverflow.com/questions/612328/difference-between-struct-and-typedef-struct-in-c) – t.niese Feb 10 '22 at 07:55
  • 1
    Since the vector is `const`, you can only obtain a `const` reference to an element. For example, `const auto &type = *starting_types.begin()` to obtain a reference to the first element. To obtain a reference to an element with index `i`, do `const auto &type = *(starting_types.begin() + i)`. Bear in mind this ASSUMES that the vector is not empty (as is the case in your code) AND that `i` is a valid index (i.e. `i` is between `0` and `starting_types.size()-1` inclusive). If either assumption is invalid, the behaviour is undefined. – Peter Feb 10 '22 at 08:48

0 Answers0