【问题标题】:Recursive data type with partly fixed types具有部分固定类型的递归数据类型
【发布时间】:2020-05-08 13:38:59
【问题描述】:

我有以下代码

#include <string_view>
#include <utility>

namespace std
{
  template <typename T1, typename T2>
  pair(T1 t1, T2 t2) -> pair<T1, T2>;
}

template<typename ... T>
struct node {};

template<typename head_t, typename ... tail_t>
struct node<head_t, tail_t ...>
{
  node(const head_t& head, const tail_t& ... tail)
    : head(head)
    , tail(tail...)
  {}

  head_t head;
  node<tail_t ... > tail;
};

template <typename... T>
node(T... t) -> node<T...>;

int main()
{
  node n{
    std::pair{std::string_view{"a"}, int{4}},
    std::pair{std::string_view{"b"}, int{5}},
    std::pair{std::string_view{"dqwd"}, node{
      std::pair{std::string_view{"asdas"}, float{3.4}}
    }
  };
  return 0;
}

我用来编译的

g++ -Wall -Wextra -Wpedantic -std=gnu++17 -Wl,--wrap=malloc

我的数据结构是std::pair 的递归列表,第一个元素类型为std::string_view。 现在我想在初始化中去掉std::pairstd::string_view,因为它们总是相同的类型,我该如何实现呢?例如:

node n{
  {"a", int{4}},
  {"b", int{5}},
  {"dqwd", node{
    {"asdas", float{3.4}}
  }
};

【问题讨论】:

  • 等一下,将用户定义的推导指南放入std命名空间是否合法?
  • 在这种情况下,无论如何都不需要pair的扣除指南。

标签: c++ c++17 template-meta-programming recursive-datastructures


【解决方案1】:

至少,摆脱string_view 非常容易。它还具有消除您对 std 命名空间的操作的好处,即使它是合法的,仍然会让我非常不舒服。

公平地说,您对std 的操作并不是那么可怕的作为示例,因为您可以轻松使用自己的std::pair 等效项并达到语法相同。

#include <string_view>

template<typename T>
auto leaf(std::string_view s, T d) {
    return std::make_pair(s, std::move(d));
}

template<typename ... T>
struct node {};

template<typename head_t, typename ... tail_t>
struct node<head_t, tail_t ...>
{
  node(head_t head, tail_t... tail)
    : head(std::move(head))
    , tail(std::move(tail)...)
  {}

  head_t head;
  node<tail_t ... > tail;
};

template <typename... T>
node(T... t) -> node<T...>;

int main()
{
    node n{
        leaf("a", 4),
        leaf("b", 5),
        leaf("c", node{
            leaf("aaa", 12.4f)
        })
    };

  return 0;
}

为了摆脱叶子,以下可能适用:https://stackoverflow.com/a/51857245/4442671,但我怀疑不是。

附带说明一下,您的节点类可以简单地委托给std::tuple&lt;&gt;,这几乎是完全相同的事情。这将使您不必处理参数的递归剥离,您甚至不需要演绎指南:

template<typename... T>
struct node
{
  node(std::pair<std::string_view, T>... args)
    : childs_(std::move(args)...) {}

  std::tuple<std::pair<std::string_view, T>...> childs_;
};

【讨论】:

  • std::tuple 的好主意!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2023-03-12
  • 2020-05-26
  • 2021-12-16
  • 1970-01-01
  • 2013-09-17
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多