请考虑以下代码,该类型可以组成不同的混合类型。组合类型的构造函数采用可变元组列表,表示组合类型构造函数的参数:
#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/