【问题标题】:result_of, make_tuple, parameter packresult_of、make_tuple、参数包
【发布时间】:2017-02-02 11:27:08
【问题描述】:

我想获得std::make_tuple 返回的给定参数包的类型。到目前为止,我已经编写了以下代码:

#include <tuple>
#include <functional>

template <class T>
struct unwrap_refwrapper
{
    using type = T;
};

template <class T>
struct unwrap_refwrapper<std::reference_wrapper<T>>
{
    using type = T&;
};

template <class T>
using special_decay_t = typename unwrap_refwrapper<typename std::decay<T>::type>::type;

template<class ... Types>
struct foo
{
    typedef std::tuple<special_decay_t<Types>...> tuple_t;
};

int main()
{
    short s;
    // t should be std::tuple<int, double&, short&>
    typedef foo<int, double&, decltype(std::ref(s))>::tuple_t t;
}

但是我觉得复制 possible implementation of std::make_tuple 的一部分非常难看,我在这里做了。

我想使用std::result_of 或类似的东西来实现给定的效果。

我的尝试如下:

#include <tuple>
#include <functional>

template<class ... Types>
struct foo
{
    typedef typename std::result_of<
        std::make_tuple(Types...)>::type tuple_t;
};

int main()
{
    short s;
    // t should be std::tuple<int, double&, short&>
    typedef foo<int, double&, decltype(std::ref(s))>::tuple_t t;
}

但它确实是not compile

怎么做?

【问题讨论】:

  • 你应该给result_of一个可调用的对象,但实际上你给它的是调用函数的结果。您可以使用 decltype 代替它。
  • 为什么需要复杂的逻辑来对make_tuple的返回类型进行逆向工程?它是指定的,而且不是很复杂。
  • @KerrekSB:我尽量避免对make_tuple 的返回类型进行逆向工程,但到目前为止没有成功。但T.C.s answer 正是我想要的。
  • 是的,没错,这个解决方案真的很不错。

标签: c++ c++11 c++14 variadic-templates template-meta-programming


【解决方案1】:
template<class... Ts>
struct foo
{
    using tuple_t = decltype(std::make_tuple(std::declval<Ts>()...));
};

【讨论】:

    猜你喜欢
    • 2018-06-20
    • 2011-12-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-16
    • 2016-08-18
    • 1970-01-01
    相关资源
    最近更新 更多