如何编写采用通用 C++ 标准库容器的模板函数 [英] How can I write a template function that takes a generic C++ standard library container

查看:40
本文介绍了如何编写采用通用 C++ 标准库容器的模板函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个函数需要能够适用于不同的容器类型,例如

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)

void foo(const std::list<bar>& param1, const std::list<double>& params2)

其中 bar 是我编写的 class.函数体本身使用通用 C++ 标准库函数.

where bar is a class that I've written. The function body itself uses generic C++ standard library functions.

有什么方法可以将其模板化吗?我试过了

Is there a way I can templatise this? I have tried

template<typename T> void foo(const T<bar>&, const T<double>&)

但这会导致编译器错误

错误 C2988:无法识别的模板声明/定义

error C2988: unrecognizable template declaration/definition

我使用的是 MSVC2015.

I'm using MSVC2015.

推荐答案

您应该将 T 声明为 模板模板参数 表示它是模板名称(并且需要实例化的参数),例如

You should declare T as template template parameter to indicate that it's a template-name (and needs arguments to be instantiated), e.g.

template<template <typename...> class T> 
void foo(const T<bar>&, const T<double>&);

直播

这篇关于如何编写采用通用 C++ 标准库容器的模板函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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