【问题标题】:Templated Fixed + Variable-Sized Class模板化的固定 + 可变大小的类
【发布时间】:2016-08-01 15:35:45
【问题描述】:

假设我有几个像这样的容器类:

template<typename T> class Container
{
    /* ... */
};

template<typename T, size_t> class Array : public Container<T>
{
    /* Fixed-sized Container */
};

template<typename T> class Vector : public Container<T>
{
    /* Variable-sized Container */
};

我有一个类接受其中一个作为模板参数:

template<typename T, template<typename> class U, size_t M> class Polygon
{
    U<T> Vertices; // Problem, what if user passes Array (it needs 2 parameters)
    U<T, M> Vertices; // Problem, what if the user wants to use a variable-sized container (it needs only 1 parameter)
};

我的问题是,我能否以某种方式(可能通过棘手的模板参数魔术)使消费类接受任何类型的容器(固定或可变大小,即使具有不同的模板签名)?

关于模板签名的唯一保证是,如果它是一个固定大小的容器,它将有两个参数&lt;Type, Size&gt;,如果它是一个可变大小的容器&lt;Type&gt;

【问题讨论】:

    标签: c++ templates containers


    【解决方案1】:

    它没有你想象的那么棘手。你可以只在容器本身上做模板:

    template <class Container>
    class Polygon {
        Container vertices;
    };
    

    这适用于满足您的容器要求的任何东西,无论大小是否固定。

    为容器选择正确的模板参数的问题被转移到实例化点,无论如何都必须知道参数和类型。

    【讨论】:

      猜你喜欢
      • 2013-06-12
      • 1970-01-01
      • 1970-01-01
      • 2016-10-29
      • 2017-04-29
      • 1970-01-01
      • 1970-01-01
      • 2011-05-11
      • 1970-01-01
      相关资源
      最近更新 更多