Chciałbym mieć schludny sposób inicjowania wielu odniesień zwracanych z funkcji poprzez std::tuple
przy użyciu std::tie
(lub std::forward_as_tuple
) - zobacz kod zabawki poniżej.Inicjowanie wielu odniesień za pomocą std :: tie
#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;
}
roztworze powyżej działa, ale mający tymczasową std::tuple
i wielokrotne std::get
S jest irytujące i byłoby wspaniale móc tego uniknąć, jeśli to możliwe (na przykład po powrocie nie-referencje).
Problem polega na tym, że nie możemy mieć zwisających referencji, więc nie można zainicjować zmiennych wcześniej. Czy jest jakiś kreator C++ 11/C++ 14, który pozwala mi inicjować referencje, jak nazywam się std::tie
? Czy też powyższe jedyne rozwiązanie?
Byłbyś zainteresowany niektóre czary C++ 17? –
Jeśli to jedyny sposób, to jestem uszy! – jaw
Wygląda na to, że chcesz [Wiązania strukturalne] (http://stackoverflow.com/documentation/c%2b%2b/487/how-to-return-several-values-from-a-function/3384/structured-bindings # t = 201608231422577108315). Niestety musisz poczekać na C++ 17. – NathanOliver