模板方法内的标准容器

An std container inside a template method(模板方法内的标准容器)
本文介绍了模板方法内的标准容器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好.

我不太清楚如何解释自己,但我相信一段代码会让你明白我的意图:

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 容器(向量、列表...).这就像 inception,但是有模板:一个模板,一个模板内,等等......

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++;
  }
}

但是,在您的特定情况下,我认为您最好只传递实例化容器,即

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

这篇关于模板方法内的标准容器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

What is the proper function for comparing two C-style strings?(比较两个 C 风格字符串的正确函数是什么?)
Image Capture with OpenCV - Select Timeout Error(使用 OpenCV 捕获图像 - 选择超时错误)
SHA256 HMAC using OpenSSL 1.1 not compiling(使用 OpenSSL 1.1 的 SHA256 HMAC 未编译)
How to make a Debian package depend on multiple versions of libboost(如何制作一个Debian包依赖于多个版本的libboost)
Why does strcpy_s not exist anywhere on my system?(为什么我系统上的任何地方都不存在 strcpy_s?)
Simplest way to get current time in current timezone using boost::date_time?(使用 boost::date_time 在当前时区获取当前时间的最简单方法?)