2

为了清楚起见,我从下面删除了构造函数和析构函数等内容,它们不会向问题添加任何内容。我有一个基类,用于为派生模板类创建一个共同的祖先。

class PeripheralSystemBase {
public:
    virtual void someFunctionThatsCommonToAllPeripherals() {}
};

template <class T, uint32_t numPeripherals = 1>
class PeripheralSystem : public PeripheralSystemBase {
public:
    PeripheralSystem() : vec(T) {}
    std::vector<T> vec;  // different types of T is the reason why I need to template this class
};

// A & B declaration & definition are irrelevant here
class A{};
class B{};

// There are multiple different derived variants of PeripheralSystem
// At the moment, each has different template parameters

template <uint32_t customisableParam1>
class DerivedSystem1 : public PeripheralSystem<A, 1> {
public:
    DerivedSystem1() : PeripheralSystem<A, 1>() {}
};

template <uint32_t customisableParam1, uint8_t customisableParam2>
class DerivedSystem2 : public PeripheralSystem<B, 1> {
public:
    DerivedSystem2() : PeripheralSystem<B, 1>() {/*maybe use customisableParam2 here */}
};

所以现在我有 2 个模板类,每个都派生自同一个祖先类,一个包含一个包含类型 A 的向量,另一个包含类型 B;每个都有不同的模板参数。到目前为止,一切都很好。

现在来回答这个问题。我希望能够创建一个容器模板,其中不包含一个或多个 PeripheralSystem 的派生版本,我想我可以使用可变参数模板来做到这一点,但我有点坚持过去一天左右的语法。在编译时,我希望能够创建容器类的实例。也许是这样的:

template< template<typename ...> class args...>
class ContainerClass {
  public:
    ContainerClass() : container({args}) {}
    std::vector<PeripheralSystem> container;
};

// possible usage
ContainerClass<DerivedSystem1<1>> cc1;
ContainerClass<DerivedSystem2<2, 3>> cc2;
ContainerClass<DerivedSystem1<1>, DerivedSystem2<2, 3>> cc3;

我知道我使用的可变参数格式不正确,因为我得到:

错误:模板参数列表模板<模板类参数...>中的预期','或'>'

我想告诉编译器的是我想为模板提供可变数量的模板类型参数,每个参数都有可变数量的模板参数。请问我可以用可变参数模板做到这一点吗?请对正确的语法有任何建议吗?

4

1 回答 1

2

你的省略号放错地方了。尝试:

template<template<typename...> class... Args>
                                    ^^^ here

但是,您实际上并不需要模板模板参数;因为DerivedSystem1<1>是类型,而不是模板,你只需要普通的类型名参数:

template<typename... Args>
class ContainerClass {

对于实际的容器,您不能使用vector<PeripheralSystem>它,因为它是同质的,并且会将派生类型切分成PeripheralSystem. 如果您添加一个虚拟析构函数,PeripheralSystem您可以使用vector<unique_ptr<PeripheralSystem>>

template<typename... Args>
class ContainerClass {
  public:
    ContainerClass() : container{std::make_unique<Args>()...} {}
    std::vector<std::unique_ptr<PeripheralSystem>> container;
};

但是,tuple也可以正常工作并导致更少的分配:

template<typename... Args>
class ContainerClass {
  public:
    ContainerClass() : container{Args{}...} {}
    std::tuple<Args...> container;
};
于 2014-07-17T20:32:57.307 回答