带有模板容器的模板类
如何将具有不同容器的模板类(适配器)声明为模板参数?例如,我需要声明类:
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
).
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;
不将模板参数传递给容器.
without passing template argument to container.
推荐答案
你应该使用模板模板参数:
template<typename T, template <typename, typename> class Container>
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
class MyMultibyteString
{
Container<T, std::allocator<T>> buffer;
// ...
};
这将允许你写:
MyMultibyteString<int, std::vector> mbs;
这是一个编译现场示例.编写上述内容的另一种方式可能是:
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
// ...
};
这是相应的现场示例.
唯一需要注意的是,模板模板参数声明中的参数数量和类型必须与要作为模板传递的相应类模板的定义中的参数数量和类型完全匹配参数,不管这些参数中的一些可能有默认值.
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
.因此,您可以不写:
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.
相关文章