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

2022-01-24 00:00:00 containers templates c++ stl

我需要一个这样的模板,效果很好

I need a template like this, which work perfectly

template <typename container> void mySuperTempalte (const container myCont)
{
    //do something here
}

然后我想将上面的模板专门用于 std::string 所以我想出了

then i want to specialize the above template for std::string so i came up with

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

这不起作用,并引发错误.我想让第二个示例工作,然后如果可能的话,我想在模板中添加一些代码来检查是否使用了 std::vector/std::deque/std::list,在每个示例中执行不同的操作案件.所以我使用了模板,因为 99% 的代码对于向量和双端队列等都是相同的.

which doesnt't work, and throws an error. I would like to make the second example work and then IF possible i would like to add some code in the template to check if a std::vector/std::deque/std::list was used, to do something differently in each case. So i used templates because 99% of the code is the same for both vectors and deques etc.

推荐答案

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

If I am understanding your problem correctly you have an algorithm that will work for STL containers vector, deque etc but are trying to write a template specialisation for string. If this is the case then you can write the generalised templated method that you defined in your question:-

template<typename container> void mySuperTempalte( const container &myCont )
{
    // Implement STL container code
}

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

Then for your string specialisation you declare:-

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

对于任何其他专业化,只需更改 myCont 的类型声明.如果您确实需要对 vector 和 deque 容器执行此操作,则将模板参数设置为该容器中类型的参数,而不是像 Sep 建议的容器本身.

For any other specialisation just change the type declaration for myCont. If you really need to do this for the vector and deque containers then make the template parameter the parameter for the type in that container rather than the container itself as Sep suggested.

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

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

It's worth trying to avoid this by making your first implementation work with all STL containers to make your life easier, then you only need the specialisation for the string class. Even consider converting your string to a vector to avoid the specialisation all together.

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

On a side note, I've changed the container parameter to a const reference, I assume this is what you want, as you declare the object const anyway, this way you avoid a copy.

相关文章