为什么这个元组对引用元组(std :: tie)的转换有效?

时间:2017-08-07 01:41:08

标签: c++ c++17 stdtuple

我正在制作一个“std :: tie-able”类。 该类用作临时对象,根据其分配的类型获取值。

这对于分配给元组是很明显的:

ts

然而,该类应该也可以与std :: tie一起使用。

// 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();

fetch_values期望值类型参数,因此上面需要更改,因为tie导致T ...是引用类型。为了达到这个目的,我最终得到了另一种转换为引用元组的方法:

int a, b;
std::tie(a, b) = get_temporary();

这确实可以编译和工作,但我有几个问题:

  • 只有在返回之前在template<typename... T> operator std::tuple<T&...>() { auto result = fetch_values<T...>(); // returns tuple<T...> return result; } 中存储fetch_values的结果时才会编译。编写result时编译失败并显示return fetch_values<T...>()。为什么这种解决方法有效?

  • 这首先有效吗? no viable conversion from returned value of type tuple<T, T> to function return type tuple<T&, T&>是否存在足够长的时间,直到值存储在result'd变量中?

Adding push notification tags from an Azure Mobile Apps client

1 个答案:

答案 0 :(得分:1)

你的两个片段都会返回悬空指针。

您只需按价值返回:

// temporary class conversion operator
template<typename... T>
operator std::tuple<T...>() const {
    return fetch_values<T...>(); // returns tuple<T...>
}

使用std::tie进行转换即可。

相关问题