問題描述
如何將具有不同容器的模板類(適配器)聲明為模板參數?例如,我需要聲明類:
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.
這篇關于帶有模板容器的模板類的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!