函数模板编译错误

时间:2014-06-13 17:33:15

标签: c++ templates

以下代码

template <typename T, class ContainerType>
ContainerType<T>::iterator elementIteratorAt(ContainerType<T> container, size_t index)
{
    return container.end();
}

在函数的返回类型(ContainerType<T>::iterator)生成编译错误:

  

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

为什么会这样,以及如何正确地写这个?我甚至没有实例化模板,只是编译。

2 个答案:

答案 0 :(得分:3)

您的代码存在两个问题。首先,ContainerType<T>::iterator是从属类型,因此您必须添加typename关键字。接下来,ContainerType应该是模板,但模板参数并不表示。您需要模板模板参数。

template <typename T, template<class...> class ContainerType>
typename ContainerType<T>::iterator 
    elementIteratorAt(ContainerType<T> container, size_t index)
{
    return container.end();
}

Live demo

我已经制作了模板模板参数variadic,因为标准库中的容器都有多个模板参数。


正如评论中所建议的那样,您也可以将其简化为

template <class ContainerType>
typename ContainerType::iterator 
    elementIteratorAt(ContainerType container, size_t index)
{
    return container.end();
}

如果您需要访问容器中的元素类型,请使用ContainerType::value_type(适用于标准库容器)。

答案 1 :(得分:0)

只要您拥有依赖类型(例如typename),就需要ContainerType<T>::iterator关键字:

template <typename T, class ContainerType>
typename ContainerType<T>::iterator elementIteratorAt(ContainerType<T> container, size_t index)