[英]How can I write a template function that takes a generic C++ standard library container
I have a function that needs to be able to work for different container types, for example 例如,我有一个功能需要能够适用于不同的容器类型
void foo(const std::vector<bar>& param1, const std::vector<double>& params2)
and 和
void foo(const std::list<bar>& param1, const std::list<double>& params2)
where bar
is a class
that I've written. bar
是我写的一个class
。 The function body itself uses generic C++ standard library functions. 函数体本身使用通用的C ++标准库函数。
Is there a way I can templatise this? 有没有办法可以扼杀这个? I have tried
我努力了
template<typename T> void foo(const T<bar>&, const T<double>&)
But this gives the compiler error 但这会给编译器带来错误
error C2988: unrecognizable template declaration/definition
错误C2988:无法识别的模板声明/定义
I'm using MSVC2015. 我正在使用MSVC2015。
You should declare T
as template template parameter to indicate that it's a template-name (and needs arguments to be instantiated), eg 您应该将
T
声明为模板模板参数,以指示它是模板名称(并且需要实例化参数),例如
template<template <typename...> class T>
void foo(const T<bar>&, const T<double>&);
There are basically three solutions: 基本上有三种解决方案:
Use template template arguments . 使用模板模板参数 。
Use iterators (which is what the standard library itself uses) 使用迭代器(这是标准库本身使用的)
Use different templates for different arguments, and let the compiler deduce the actual types. 对不同的参数使用不同的模板,让编译器推导出实际的类型。 With your function it would be something like
有了你的功能,它就像是
template<typename T, typename U> void foo(const T&, const U&);
Solution 2 is the recommended one if you just need to iterate over the contents of the container. 如果您只需要迭代容器的内容,建议使用解决方案2。 Solution 3 is the recommended one if you need access tot he container itself.
如果您需要访问容器本身,建议使用解决方案3。
So-called template template arguments will allow you to write the desired code (as also shown in other answers or over on CppReference ). 所谓的模板模板参数将允许您编写所需的代码(如其他答案或CppReference中所示 )。
Alternatively, you could also write generic functions that accept iterators . 或者,您也可以编写接受迭代器的泛型函数。 This is exactly how the functions in the
<algorithm>
are implemented. 这正是
<algorithm>
中的函数的实现方式。 I tend to believe that functions that accept iterators are actually more flexible as the caller can decide what range needs to be processed by the function. 我倾向于认为接受迭代器的函数实际上更灵活,因为调用者可以决定函数需要处理的范围。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.