Reputation: 7388
I'm in the process of making a class "std::tie-able". The class serves as a temporary object that fetches values depending on the type it's assigned to.
This is obvious to implement for assignment to a tuple:
// temporary class conversion operator
template<typename... T>
operator std::tuple<T...>() {
return fetch_values<T...>(); // returns tuple<T...>
}
// usage:
std::tuple<int, int> = get_temporary();
However the class is supposed to be able to be used with std::tie as well.
int a, b;
std::tie(a, b) = get_temporary();
fetch_values expects value type arguments, so the above needs changes since tie results in T... being reference types. To achieve this I've ended up with an additional method for conversion to tuple-of-references:
template<typename... T>
operator std::tuple<T&...>() {
auto result = fetch_values<T...>(); // returns tuple<T...>
return result;
}
This does compile and work, but I have a couple of questions:
It only compiles when storing the result of fetch_values in result
before returning it. When writing return fetch_values<T...>()
the compilation fails with no viable conversion from returned value of type tuple<T, T> to function return type tuple<T&, T&>
. Why does this workaround work?
Is this valid to do in the first place? Does result
live long enough until after the values are stored in the std::tie
'd variables?
Upvotes: 2
Views: 816
Reputation: 218333
your both snippets returns dangling pointer.
You should simply return by value:
// temporary class conversion operator
template<typename... T>
operator std::tuple<T...>() const {
return fetch_values<T...>(); // returns tuple<T...>
}
The conversion with std::tie
will work.
Upvotes: 1