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

这很明显可以实现分配给元组:

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

但是,该类也应该能够与std::tie一起使用。
int a, b;
std::tie(a, b) = get_temporary();

fetch_values需要使用值类型参数,因此上述内容需要更改,因为tie导致T ...为引用类型。为了实现这一点,我最终得到了一种转换为引用元组的附加方法:
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变量中之前,std::tie是否寿命足够长?

  • Example showing the issue

    最佳答案

    您的两个摘要都返回悬空的指针。

    您应该只按值返回:

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

    使用std::tie的转换将起作用。

    关于c++ - 为什么这个元组到引用元组(std::tie)转换有效?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/45538312/

    10-11 16:49