使用带递归的std :: variant,而不使用boost :: recursive_wrapper

sms*_*sms 21 c++ boost c++17

我想boost::variant用C++ 17 替换s std::variant并摆脱boost::recursive_wrapper,在下面的代码中完全消除对boost的依赖.我该怎么办?

#include <boost/variant.hpp>
#include <type_traits>

using v = boost::variant<int, boost::recursive_wrapper<struct s> >;
struct s
{
    v val;
};

template<template <typename...> class R, typename T, typename ... Ts>
auto reduce(T t, Ts ... /*ts*/)
{
    return R<T, Ts...>{t};
}

template<typename T, typename F>
T adapt(F f)
{
    static_assert(std::is_convertible_v<F, T>, "");
    return f;
}

int main()
{
    int  val1 = 42;
    s    val2;
    auto val3 = adapt<v>(reduce<boost::variant>(val1, val2));
}
Run Code Online (Sandbox Code Playgroud)

有两个通用函数:第一个函数reduce在运行时选择返回哪个参数(这里它只返回第一个参数以便简洁),第二个函数adapt将类型F的值转换为类型T的值.

在此示例中,reduce返回一个类型的对象,boost::variant<int, s>然后将其转换为类型的对象boost::variant<int, boost::recursive_wrapper<s> >.

Yak*_*ont 17

boost::variant将堆分配,以便将其自身的一部分递归地定义为自身.(它还会在许多其他情况下分配堆,不确定多少)

std::variant将不会. std::variant拒绝堆分配.

如果没有动态分配,就没有办法实际拥有包含自身可能变体的结构,因为如果静态声明,这样的结构可以很容易地显示为无限大小.(您可以通过N次递归来编码整数N:没有固定大小的缓冲区可以容纳无限量的信息.)

因此,等价物std::variant存储自身递归实例的某种占位符的智能指针.

这可能有效:

struct s;
using v = std::variant< int, std::unique_ptr<s> >;
struct s
{
  v val;
  ~s();
};
inline s::~s() = default;
Run Code Online (Sandbox Code Playgroud)

如果没有,请尝试:

struct destroy_s;
struct s;
using v = std::variant<int, std::unique_ptr<s, destroy_s> >;
struct s
{
  v val;
  ~s();
};
struct destroy_s {
  void operator()(s* ptr){ delete ptr; }
};
inline s::~s() = default;
Run Code Online (Sandbox Code Playgroud)

它确实意味着客户端代码必须有意识地与unique_ptr<s>而不是struct s直接交互.

如果你想支持复制语义,你必须写一个value_ptr副本语句,并给它相当于struct copy_s;实现该副本.

template<class T>
struct default_copier {
  // a copier must handle a null T const* in and return null:
  T* operator()(T const* tin)const {
    if (!tin) return nullptr;
    return new T(*tin);
  }
  void operator()(void* dest, T const* tin)const {
    if (!tin) return;
    return new(dest) T(*tin);
  }
};
template<class T, class Copier=default_copier<T>, class Deleter=std::default_delete<T>,
  class Base=std::unique_ptr<T, Deleter>
>
struct value_ptr:Base, private Copier {
  using copier_type=Copier;
  // also typedefs from unique_ptr

  using Base::Base;

  value_ptr( T const& t ):
    Base( std::make_unique<T>(t) ),
    Copier()
  {}
  value_ptr( T && t ):
    Base( std::make_unique<T>(std::move(t)) ),
    Copier()
  {}
  // almost-never-empty:
  value_ptr():
    Base( std::make_unique<T>() ),
    Copier()
  {}

  value_ptr( Base b, Copier c={} ):
    Base(std::move(b)),
    Copier(std::move(c))
  {}

  Copier const& get_copier() const {
    return *this;
  }

  value_ptr clone() const {
    return {
      Base(
        get_copier()(this->get()),
        this->get_deleter()
      ),
      get_copier()
    };
  }
  value_ptr(value_ptr&&)=default;
  value_ptr& operator=(value_ptr&&)=default;

  value_ptr(value_ptr const& o):value_ptr(o.clone()) {}
  value_ptr& operator=(value_ptr const&o) {
    if (o && *this) {
      // if we are both non-null, assign contents:
      **this = *o;
    } else {
      // otherwise, assign a clone (which could itself be null):
      *this = o.clone();
    }
    return *this;
  }
  value_ptr& operator=( T const& t ) {
    if (*this) {
      **this = t;
    } else {
      *this = value_ptr(t);
    }
    return *this;
  }
  value_ptr& operator=( T && t ) {
    if (*this) {
      **this = std::move(t);
    } else {
      *this = value_ptr(std::move(t));
    }
    return *this;
  }
  T& get() { return **this; }
  T const& get() const { return **this; }
  T* get_pointer() {
    if (!*this) return nullptr;
    return std::addressof(get());
  }
  T const* get_pointer() const {
    if (!*this) return nullptr;
    return std::addressof(get());
  }
  // operator-> from unique_ptr
};
template<class T, class...Args>
value_ptr<T> make_value_ptr( Args&&... args ) {
  return {std::make_unique<T>(std::forward<Args>(args)...)};
}
Run Code Online (Sandbox Code Playgroud)

活生生的例子 value_ptr的.

  • @Yakk:我不同意你的结论。是的,“Boost.Variant”有时会进行堆分配。但这并不是其变体类型允许递归的原因;这一切都是通过“recursive_wrapper”完成的,它实现了“value_ptr”的有效等价物。标准库可以提供类似的 recursive_wrapper 类,而不会影响 `std::variant` 的定义。事实上,您可以毫无问题地将“boost::recursive_wrapper”与“std::variant”一起使用。 (3认同)
  • 为了避免使用 boost 优秀的 recursive_wrapper,这似乎是一个很大的麻烦。证实了我的立场,即提升是一个比标准更好的标准。 (3认同)
  • @sms第1段和第2段对此进行了解释:因为决定`std :: variant`不使用堆.第3段总结了为什么`std :: variant`无法使用你想要的递归结构,无论你使用什么技巧.`std :: variant`与`boost :: variant`具有不同的操作语义.除此之外,它几乎是永不空的,而不是像'boost`那样永不空.`boost :: variant`的成本是它会更频繁地调用相当于`new`的方式,而`std :: variant`是一个标记的联合,它将数据存储在自身中.`value_ptr`提供了一个解决方案. (2认同)