使用模板参数中定义的类型 [英] Using types defined in template arguments

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

问题描述

当使用像向量 list 等容器类时,我可以使用元素的类型通过写向量< type> :: value_type

When using a container class like vector, list, etc., I can use the type of the elements by writing vector<type>::value_type.

但是,以下代码

template<class container>
void foo(container& c)
{
    typedef container::value_type elementtype;
    elementtype b;
}

失败,并显示错误期望的初始化器之前的'elementtype'
当容器类型作为模板参数给出时,我是否可以推断元素类型,或者我必须将元素类型作为额外的模板参数?

fails with the error "expected initializer before ‘elementtype’". Is it possible to infer the element type when the container type is given as a template argument or do I have to give the element type as an extra template argument?

推荐答案

您缺少必需的typename关键字:

You're missing the required typename keyword:

typedef typename container::value_type elementtype;

这是因为 container 依赖名称,因此编译器无法知道container :: value_type是否总是一个类型,因为它可能取决于 container

This is because container is a dependent name in this template, so the compiler has no way of knowing whether container::value_type is always a type or not, as it may depend on the choice of container.

当然这个问题是常见问题吗?

Surely this question is a FAQ somewhere?

编辑, =http://www.parashift.com/c++-faq-lite/templates.html#faq-35.18 =nofollow> http://www.parashift.com/c++-faq-lite/templates。 html#faq-35.18

Edit, it is: http://www.parashift.com/c++-faq-lite/templates.html#faq-35.18

这篇关于使用模板参数中定义的类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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