【问题标题】:Is there a way to convert a list of lvalues and rvalues to a tuple of tuples with reference types and full types respectively?有没有办法将左值和右值列表分别转换为具有引用类型和完整类型的元组?
【发布时间】:2017-10-27 14:42:30
【问题描述】:

这是问题Is there a way to convert a list of lvalues and rvalues to a tuple with reference types and full types respectively?的第二部分

我想根据参数列表的左值/右值类型创建一个元组(或对)的元组。这是我目前所拥有的:

#include <tuple>
using LPCWSTR = wchar_t const*;

namespace detail
{
    template <typename T>
    struct VarVal : std::pair<LPCWSTR, T>
    {
        // Importing the base constructors so I don't have to redefine them
        using std::pair<LPCWSTR, T>::pair;
        VarVal(VarVal const&) = delete; // copy could be made valid, but I don't want it copied around.
        VarVal(VarVal&&) = default; // would rather that no copying/moving be done, but not sure how
    };
}

// lvalue
template <typename T>
detail::VarVal<std::reference_wrapper<T&>> vv(LPCWSTR var, T& val)
{
    return{ var, val };
}

// rvalue
template <typename T>
detail::VarVal<T const> vv(LPCWSTR var, T&& val)
{
    return{ var, val };
}

struct SomeType
{
    int x;
    auto GetLeft()   const { return  1; }
    auto& GetRight()  const { return  x; }
};

auto varvals(SomeType const& object)
{
    return make_tuple(
        vv( L"left",  object.GetLeft() ),
        vv( L"right", object.GetRight() )
    );
}

Demo

这适用于右值,但是当我将它用于左值时,它会说reference_wrapper&lt;T&gt; requires T to be an object type or a function type.

我错过了什么?

【问题讨论】:

    标签: c++11 templates visual-c++


    【解决方案1】:

    我错过了什么?

    template <typename T>
    detail::VarVal<std::reference_wrapper<T>> vv(LPCWSTR var, T& val)
    {
        return{ var, val };
    }
    

    std::reference_wrapper&lt;T&gt;,不是std::reference_wrapper&lt;T&amp;&gt;

    【讨论】:

    • 必须剥夺睡眠。谢谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-23
    • 2021-02-15
    • 2015-05-26
    相关资源
    最近更新 更多