模板化固定+可变大小类 [英] Templated Fixed + Variable-Sized Class

查看:57
本文介绍了模板化固定+可变大小类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Let's say I have several container classes like these:

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 */
};

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

And I have a class which accepts one of these as a template parameter:

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)
};

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

My question is, can I somehow (probably through tricky template parameter magic) make the consuming class accept any type of container (fixed or variable-sized, even with differing template signatures)?

关于模板签名的唯一保证是,如果它是固定大小的容器,将具有2个参数< Type,Size> 和一个参数,如果它是一个可变大小的容器< Type>

The only guarantees about the template signatures are, if it is a Fixed-sized container it will have 2 parameters <Type, Size> and one if it is a Variable-sized container <Type>

推荐答案

这比您想象的要棘手得多。您可以只在容器本身上做模板:

It's way less tricky than you think it is. You can just template on the container itself:

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

这将满足所有满足您的容器要求的东西,无论尺寸是否固定。

This will work for anything that meets your container requirements, be it fixed sized or not.

为容器选择正确的模板参数的问题已转移到必须始终知道参数和类型的实例化点。

The problem of choosing the right template arguments for the container gets moved to instantiation point where the parameters and types must be known anyways.

这篇关于模板化固定+可变大小类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆