与模板容器的模板类 [英] Template class with template container
问题描述
如何声明具有不同容器的模板类(适配器)作为模板参数?
例如,我需要声明类:
How can I declare template class (adaptor) with different containers as template arguments? For example, I need to declare class:
template<typename T, typename Container>
class MyMultibyteString
{
Container buffer;
...
};
我想要的基于矢量。如何使它硬定义? (以防止某人写这样的声明 MyMultibyteString< int,vector< char>>
)。
And I want it to my based on vector. How to make it hard-defined? (to prevent someone from writing such declaration MyMultibyteString<int, vector<char>>
).
此外,如何实现此类构造:
Moreover, how to implement such construction:
MyMultibyteString<int, std::vector> mbs;
。
推荐答案
您应该使用模板模板参数:
template<typename T, template <typename, typename> class Container>
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
class MyMultibyteString
{
Container<T, std::allocator<T>> buffer;
// ...
};
这将允许您写:
MyMultibyteString<int, std::vector> mbs;
这里是一个编译 live example 。编写上述代码的另一种方式可以是:
Here is a compiling live example. An alternative way of writing the above could be:
template<typename T,
template <typename, typename = std::allocator<T>> class Container>
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
class MyMultibyteString
{
Container<T> buffer; // <== No more need to specify the second argument here
// ...
};
And here is the corresponding live example.
您必须注意的唯一事情是模板模板中参数的数量和类型参数声明必须完全匹配要作为模板参数传递的相应类模板的定义中的参数的数量和类型,而不管这些参数中的一些参数可能具有默认值。
The only thing you have to pay attention to is that the number and type of arguments in the template template parameter declaration must match exactly the number and type of arguments in the definition of the corresponding class template you want to pass as a template argument, regardless of the fact that some of those parameters may have default values.
例如,类模板 std :: vector
接受两个模板参数(元素类型和分配器类型),虽然第二个具有默认值 std :: allocator< T>
。因此,您可以不写:
For instance, the class template std::vector
accepts two template parameters (the element type and the allocator type), although the second one has the default value std::allocator<T>
. Because of this, you could not write:
template<typename T, template <typename> class Container>
// ^^^^^^^^
// Notice: just one template parameter declared!
class MyMultibyteString
{
Container<T> buffer;
// ...
};
// ...
MyMultibyteString<int, std::vector> mbs; // ERROR!
// ^^^^^^^^^^^
// The std::vector class template accepts *two*
// template parameters (even though the second
// one has a default argument)
这意味着你不能写一个可以接受 std :: set
和 std :: vector
作为模板模板参数的单类模板,因为不同于 std :: vector
, std :: set
类模板接受三个模板参数。
This means that you won't be able to write one single class template that can accept both std::set
and std::vector
as a template template parameter, because unlike std::vector
, the std::set
class template accepts three template parameters.
这篇关于与模板容器的模板类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!