I'd like to have a neat way of initializing multiple references returned from a function via std::tuple using std::tie (or std::forward_as_tuple)—see toy code below.
#include <tuple>
#include <iostream>
class Foo
{
public:
Foo () : m_memberInt(5), m_anotherMemberInt(7) {}
void IncrementMembers() {++m_memberInt; ++m_anotherMemberInt;}
std::tuple<int &, int &> GetMembers() {return std::tie(m_memberInt, m_anotherMemberInt);}
private:
int m_memberInt;
int m_anotherMemberInt;
};
int main()
{
Foo foo;
// Can't have dangling references.
// int &x, &y;
// std::tie(x, y) = foo.GetMembers();
std::tuple<int &, int &> tmpTuple = foo.GetMembers();
int &x = std::get<0>(tmpTuple);
int &y = std::get<1>(tmpTuple);
std::cout << x << " " << y << std::endl;
foo.IncrementMembers();
std::cout << x << " " << y << std::endl;
return 0;
}
The solution above works but having the temporary std::tuple and multiple std::gets is annoying and it would be great to be able to avoid this if possible (like when returning non-references).
The issue is that we can't have dangling references so can't initialize the variables beforehand. Is there some C++11/C++14 wizardry to allow me to initialize references as I call std::tie? Or is the above the only solution?
Aucun commentaire:
Enregistrer un commentaire