模板方法中的std容器 [英] An std container inside a template method

查看:73
本文介绍了模板方法中的std容器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问候。

我不太清楚如何解释自己,但我相信一段代码会使您理解我的意图:

I don't know very well how to explain myself, but I believe a piece of code will make you understand what I'm intenting to do :

template<class A, class B>
void myFunction(A<B>& list)
{
  typename A<B>::iterator current = list.begin();
  typename A<B>::iterator end = list.end();

  while (current != end)
  {
    current++;
  }
}

其中A是STL容器(向量,列表。 ..)。就像是开始,但是有了模板:模板,模板内部等等……

Where A is an STL container (vector, list...). It's like inception, but with templates : a template, inside a template, etc...

问题是:当模板的一个参数发生时,您会怎么做本身就是一个模板...并且仍然希望支持该模板支持的每种类型。

The thing is : what do you do when one of the params of your template is itself a template... and still want to support every types supported by this template.

这当然不会编译(它说 A不是模板 ')。

This of course doesn't compile (it says 'A is not a template').

有人知道如何创建这样的模板吗?

Does someone knows how to create such a template ?

推荐答案

您正在寻找模板模板参数

You are looking for a template template parameter

template<template<class T, class All = std::allocator<T> > class A, class B>
void myFunction(A<B>& list)
{
  typename A<B>::iterator current = list.begin();
  typename A<B>::iterator end = list.end();

  while (current != end)
  {
    current++;
  }
}

但是,在您的特定情况下,我认为您是d只需通过实例化容器即可,

However, in your particular case, I think you'd be better off by just passing the intantiated container, that is,

template<class C>
void myFunction(C& list)
{
   ...
}

像这样使用

vector<char> v;
myFunction(v);

您的原始代码必须像这样被调用:

Your original code would have to be called like this:

myFunction<std::vector, char> (v)

更为冗长,没有特别的好处

which is much more verbose and has no particular benefit

这篇关于模板方法中的std容器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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