适用于STL容器的简单C++模板

SMe*_*ers 4 c++ containers templates stl

我需要一个这样的模板,它可以很好地工作

template <typename container> void mySuperTempalte (const container myCont)
{
    //do something here
}
Run Code Online (Sandbox Code Playgroud)

那么我想专门为std :: string上面的模板,所以我想出了

template <typename container> void mySuperTempalte (const container<std::string> myCont)
{
    //check type of container
    //do something here
}
Run Code Online (Sandbox Code Playgroud)

哪个不起作用,并抛出一个错误.我想让第二个例子起作用然后如果可能我想在模板中添加一些代码以检查是否使用了std :: vector/std :: deque/std :: list,在每个中执行不同的操作案件.所以我使用了模板,因为99%的代码对于矢量和deques等都是相同的.

sep*_*sep 7

专业化:

template<> void mySuperTempalte<std:string>(const std::string myCont)
{
    //check type of container
    //do something here
}
Run Code Online (Sandbox Code Playgroud)

专门用于矢量:

template<typename C> void mySuperTempalte (std::vector<C> myCont)
{
    //check type of container
    //do something here
}
Run Code Online (Sandbox Code Playgroud)

专门为deque:

template<typename C> void mySuperTempalte (std::deque<C> myCont)
{
    //check type of container
    //do something here
}
Run Code Online (Sandbox Code Playgroud)


Kon*_*lph 7

你试过模板typename参数吗?语法有点奇怪,因为它模拟了用于声明这样一个容器的语法.有一篇很好的InformIT文章更详细地解释了这一点.

template <template <typename> class Container>
void mySuperTemplate(Container<std::string> const& cont) {
}
Run Code Online (Sandbox Code Playgroud)

请注意,您还应该将参数声明为引用!

顺便说一下:这个评论

//check type of container
Run Code Online (Sandbox Code Playgroud)

你做错了,是一个死的赠品.你不是要检查的容器的类型.用户更复杂的重载,如sep的答案所示.

  • _NOT_使用此代码,因为它不适用于STL容器.vector,list等不是单个参数模板,它们是至少有两个args的模板,除了第一个之外的所有模板都有默认值(允许无限数量的额外args作为实现细节).此代码不可移植. (3认同)

小智 5

如果我正确理解你的问题,你有一个算法可以用于STL容器vector,deque等,但是正在尝试为字符串编写模板特化.如果是这种情况,那么您可以编写在问题中定义的通用模板化方法: -

template<typename container> void mySuperTempalte( const container &myCont )
{
    // Implement STL container code
}
Run Code Online (Sandbox Code Playgroud)

然后为你的字符串专业化声明: -

template<> void mySuperTempalte( const container<std::string> &myCont )
{
    // Implement the string code
}
Run Code Online (Sandbox Code Playgroud)

对于任何其他专业化,只需更改myCont的类型声明即可.如果你真的需要为vector和deque容器执行此操作,那么将template参数作为该容器中类型的参数,而不是Sep建议的容器本身.

template<typename C> void mySuperTempalte( const std::vector<C> &myCont)
{
    // check type of container
    // do something here
}
Run Code Online (Sandbox Code Playgroud)

值得尝试通过使您的第一个实现与所有STL容器一起工作以使您的生活更轻松来避免这种情况,然后您只需要字符串类的专门化.甚至考虑将您的字符串转换为向量以避免专业化.

在旁注中,我已经将容器参数更改为const引用,我假设这是您想要的,因为您无论如何都声明了对象const,这样您就可以避免复制.