I have something like this (C 11)
std::tuple<const MyType&, bool> func()
{
return std::make_tuple(some_internal_reference, true);
}
the problem is that in the caller I cannot declare:
const MyType& obj; // this does not compile of course
bool b;
std::tie(obj, b) = func();
An idea is to return the boolean as an output param and drop the tuple, but is there a better solution?
CodePudding user response:
Use std::get
. It returns reference to stored element.
#include <iostream>
#include <tuple>
using MyType = int;
MyType some_internal_reference = 42;
std::tuple<const MyType&, bool> func()
{
return { some_internal_reference, true };
}
int main()
{
auto ret = func();
const MyType& obj = std::get<0>(ret);
std::cout << "before change: " << obj << '\n';
some_internal_reference = 7;
std::cout << "after change: " << obj << '\n';
}
It prints
before change: 42
after change: 7
Note, as per @StoryTeller-UnslanderMonica comment, don't use std::make_tuple
in this case. It stores a decay (naked type) copy.