c++ - 是否可以在以下代码中避免对复制/移动构造函数的需要?

标签 c++ templates c++17 variadic-templates

请考虑以下代码,该类型可以组成不同的混合类型。组合类型的构造函数采用可变元组列表,表示组合类型构造函数的参数:

#include <string>
#include <tuple>
#include <utility>

struct MixinBase {
  MixinBase() = default;
  // Note; want to delete these instead of default them.
  MixinBase(const MixinBase&) = default;
  MixinBase(MixinBase&&) = default;
};

struct MixinA : public MixinBase {
  MixinA(int, const std::string&, const std::string&) {}
};

struct MixinB : public MixinBase {
  MixinB(const std::string&, const std::string&) {}
};

template <typename... Mixins>
struct Composition : private Mixins... {
  template <typename... Packs>
  Composition(Packs&&... packs)
      : Mixins(constructMixin<Mixins>(
            std::forward<Packs>(packs),
            std::make_index_sequence<std::tuple_size_v<Packs>>{}))...
  {
  }

private:
  template <typename Mixin, typename Pack, size_t... Indexes>
  Mixin constructMixin(Pack&& arguments, std::index_sequence<Indexes...>) const
  {
    return Mixin(std::get<Indexes>(std::forward<Pack>(arguments))...);
  }
};

int main()
{
  std::string a{"a"};
  std::string b{"b"};

  Composition<MixinA, MixinB>(
      std::forward_as_tuple(7, a, b), std::forward_as_tuple(a, b));

  return 0;
}

这工作得很好,但是,我想避免通过 constructMixin 的间接访问,并直接构造每个继承的 mixin 对象,这样就可以在 mixin 类型上需要一个复制/移动构造函数避免了。这可能吗?

最佳答案

你可以定义一个辅助类来支持分段构造:

template <typename T>
struct Piecewise_construct_wrapper : T {
    template <typename Tuple>
    Piecewise_construct_wrapper(Tuple&& t) : 
        Piecewise_construct_wrapper(std::forward<Tuple>(t), 
                                    std::make_index_sequence<std::tuple_size_v<Tuple>>{}) {}

    template <typename Tuple, size_t... Indexes>
    Piecewise_construct_wrapper(Tuple&& t, std::index_sequence<Indexes...>) : 
        T(std::get<Indexes>(std::forward<Tuple>(t))...) {}
};

然后你可以制作你的Composition继承Piecewise_construct_wrapper<Mixins>... :

template <typename... Mixins>
struct Composition : private Piecewise_construct_wrapper<Mixins>... {
    template <typename... Packs>
    Composition(Packs&&... packs)
        : Piecewise_construct_wrapper<Mixins>(std::forward<Packs>(packs))...
    {
    }
};

关于c++ - 是否可以在以下代码中避免对复制/移动构造函数的需要?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52006593/

相关文章:

c++ - 检查文本文件中的多条评论并打印出来

c++ - 如何支持 Variant 类型的隐式转换,例如从 int 到 unsigned long?

c++ - 如何在 C++ 中使用 std::optional

c++ - 在 MFC 中将 CString 数组转换为整数数组

c++ - 放大鼠标的算法(OpenGL)

eclipse - 在 Eclipse 中定制新的 JUnit 模板?

php - Woocommerce 商店页面自定义模板

c++ - 当主 GUI 线程被阻塞时,如何从工作线程创建无模式对话框?

C++:为什么 'delete' 内存比 'new' 内存慢太多

C++模板函数重载