0

如果库不知道基类(客户端知道),那么处理它的构造函数并不难。代码如下所示:

template<typename Parent>
struct AAAAA : public Parent
{
    using Parent::Parent;

    template<typename ...Args>
    AAAAA(int a, int b, Args ...args) : Parent(args...) {}
};

如果所有> 1个基类都是未知的,那么最好的方法是什么?

template<typename P1, typename P2>
struct AAAAA : public P1, public P2
{
    // ...CTOR....???
};

我的第一个想法是:

  • 参数包“拆分”类型。
  • 2 个转换为参数包的元组。

对于这两种想法,我不知道这次如何,以及是否可能。

4

2 回答 2

1

您可以要求客户端提供已构建的对象。它很容易理解,不需要太多打字。这要求它们是可移动构造的。

#include <iostream>
#include <utility>

struct foo { 
    foo(int x, double y) { std::cout << x << ' ' << y << '\n'; }
};

struct bar { 
    bar(const std::string& x) { std::cout << x << '\n'; }
};

template<typename P1, typename P2>
struct A : public P1, public P2 {
    A(P1&& p1, P2&& p2) : P1(std::move(p1)), P2(std::move(p2)) {}
};

int main() {
    A<foo, bar> afb({1, 2.3}, {"hello"});
}
于 2020-02-12T23:00:33.080 回答
1

在这里派上用场的是std::make_from_tuple.

这是您可以将元组用于单亲的方式:

#include <tuple>
struct foo { 
    foo(int,double){}
    foo(const foo&) = delete;
    foo(foo&&) = default;     
};

template<typename Parent>
struct A : public Parent
{
    template<typename T>
    A(const T& args) : Parent(std::make_from_tuple<Parent>(args)) {}
};

int main() {
    A<foo> a{std::make_tuple(1,2.0)};
}

添加第二个父母应该很简单。

请注意,Parent它必须至少是可移动构造的才能使这项工作。

于 2020-02-12T22:12:48.197 回答