简单的C ++模板适用于STL容器 [英] simple C++ templates suited for STL Containers

查看:118
本文介绍了简单的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%的代码是相同的向量和deques等。

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容器矢量,deque等,但试图写一个模板专业化的字符串。如果是这种情况,那么您可以编写在您的问题中定义的通用模板方法:

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.

这篇关于简单的C ++模板适用于STL容器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆