【问题标题】:How would I implement a function to extract the elements of this class?我将如何实现一个函数来提取这个类的元素?
【发布时间】:2016-05-09 18:56:49
【问题描述】:

我在 C++ 中实现元组是为了好玩,但由于下面的类对其进行了修改,因此我可以轻松地使用模板提取每个元素,只使用索引来提取每个元素。类似于 std::get。

TL;DR:提取元组内元素的实现是什么样的?

template<typename first_t, typename ... arg_v>
class Tuple : public Tuple<arg_v ...>
{
public:

    Tuple()
    {
    }

    Tuple(const first_t&& A) :
        element(A)
    {
    }

    Tuple(const first_t& A, arg_v& ... args) :
        element(A), Tuple<arg_v ...>::Tuple(args ...)
    {
    }

    Tuple(const first_t&& A, arg_v&& ... args) :
        element(A), Tuple<arg_v ...>::Tuple(args ...)
    {
    }

    first_t element;
};

template<typename last_t>
class Tuple<last_t>
{
public:
    Tuple()
    {
    }

    Tuple(const last_t& A) :
        element(A)
    {
    }

    Tuple(const last_t&& A) :
        element(A)
    {
    }
    last_t element;
};

【问题讨论】:

  • 可以看boost::tuple或者std::tuple的源码进行指导。
  • 你的移动构造函数不正确 - const&amp;&amp; 不是你可以移动的东西,然后你无论如何也不能移动任何东西。

标签: c++ templates tuples generic-programming


【解决方案1】:

我使用了递归方法。 我知道指向void 的指针是邪恶的,但是我们不知道会返回哪种类型,只有使用代码的人知道;只有最后一个 get 才能执行到我们想要的类型的转换。

请记住,此代码会将 void* 转换为您想要的内容,而无需任何检查。

class Tuple : public Tuple<arg_v ...>
{
    template<typename T>
    void get(int index, T& out)
    {
        out = *static_cast<T*>(get(index));
    }

    void* get(unsigned int index)
    {
        if (index == 0)
            return &element;
        else
            return Tuple<arg_v ...>::get(index - 1);
    }
};
class Tuple<last_t>
{
    void* get(unsigned int)
    {
        return &element;
    }
};

【讨论】:

  • static_cast&lt;Tuple&lt;arg_v ...&gt;&gt; 复制一份
  • 我改变了它,现在它可以访问没有强制转换的基类。谢谢。
猜你喜欢
  • 1970-01-01
  • 2011-07-16
  • 2020-07-24
  • 1970-01-01
  • 1970-01-01
  • 2021-05-07
  • 2012-03-18
  • 2011-05-06
  • 1970-01-01
相关资源
最近更新 更多