试图定义一个接受模板参数的模板函数 [英] Trying to define a template function that takes a template argument

查看:34
本文介绍了试图定义一个接受模板参数的模板函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试定义一个接受容器的模板函数,它也是一种模板类型.我需要知道容器的模板类型是什么 (E)(以便我可以在代码中引用它,例如 E element = *iterator;).这是我的尝试:

I'm trying to define a template function that takes a container, which is also a template type. I need to know what the template type of the container is (E) (so I can refer to it in the code, e.g. E element = *iterator;). Here's my attempt:

template <template <typename E> T>
void sort(T& container){ ... }

我认为这意味着sort 是一个模板函数,它接受一个模板参数 T.T 是一个模板类型,它接受一个模板参数 E".

I think this means "sort is a template function that takes a template argument T. T is a template type that takes a template argument E".

但是我得到了错误:

expected 'class' before T.

当我把类"放在那里时,它说:

When I put 'class' there, it says:

variable or field 'sort' declared void

我在语法上做错了什么?

What am I doing wrong with the syntax?

推荐答案

还有其他方法可以实现相同的功能.您需要的是 template template 参数.一个工作示例是:

There are other ways to achieve the same function. What you need is a template template parameter. A working example is:

template <typename E, template <typename> class T>
void sort(T<E>& container){}
main(){}

在模板签名中,T 被声明为接受另一个类型参数的(依赖)类型.该参数本身 (E) 需要声明并提供给 T,就像您在 vector 中使用的一样.

In the template signature, T is declared to be a (dependent) type that takes another type parameter. That parameter itself (E) needs to be declared and supplied to T, just as you would use in vector<int>.

您也可以使用:

    template <typename E, template <typename, typename...> class T>

如果您的容器类型需要可选参数,例如特征.

if your container type expects optional parameters such as traits.

这篇关于试图定义一个接受模板参数的模板函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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