C++ 函数模板编译错误

C++ 函数模板编译错误,c++,templates,C++,Templates,下面的代码 template <typename T, class ContainerType> ContainerType<T>::iterator elementIteratorAt(ContainerType<T> container, size_t index) { return container.end(); } 模板 ContainerType::迭代器元素迭代器(ContainerType容器,大小索引) { 返回容器。end();

下面的代码

template <typename T, class ContainerType>
ContainerType<T>::iterator elementIteratorAt(ContainerType<T> container, size_t index)
{
    return container.end();
}
模板
ContainerType::迭代器元素迭代器(ContainerType容器,大小索引)
{
返回容器。end();
}
在函数的返回类型(
ContainerType::iterator
)处生成编译错误:

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


为什么会发生这种情况,如何正确地编写?我甚至没有实例化模板,只是编译。

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

模板
typename ContainerType::迭代器元素迭代器(ContainerType容器,大小索引)

您的代码有两个问题。首先,
ContainerType::iterator
是一个依赖类型,因此必须添加
typename
关键字。接下来,
ContainerType
应该是一个模板,但template参数没有指明这一点。您需要一个模板参数

template <typename T, template<class...> class ContainerType>
typename ContainerType<T>::iterator 
    elementIteratorAt(ContainerType<T> container, size_t index)
{
    return container.end();
}
模板
typename容器类型::迭代器
elementIteratorAt(容器类型容器,大小索引)
{
返回容器。end();
}

我将模板参数设置为可变的,因为标准库中的容器都有多个模板参数

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

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

template <class ContainerType>
typename ContainerType::iterator 
    elementIteratorAt(ContainerType container, size_t index)
{
    return container.end();
}
模板
typename容器类型::迭代器
elementIteratorAt(容器类型容器,大小索引)
{
返回容器。end();
}

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

顺便说一句,这是一个函数模板,不是模板函数。无论如何,请看。@chris:Hm。在我的语言中,这当然是“模板函数”。@VioletGiraffe不,这绝对是一个函数模板。类似地,有类模板,但没有模板classes@Praetorian字体也许你对英语术语的理解是对的,我会读下去的。只是解释我为什么这么写。这样也更有意义。这是一个模板类型的函数;首先是函数,然后是模板。无论如何,在阅读了您认为重复的问题后,我仍然无法使我的代码编译。@VioletGiraffe这也发生在我身上几次:)有道理,但没有帮助。同样的错误。哦,模板编程的刺激!或者干脆
模板typename ContainerType::iterator elementiterator(ContainerType container,size\u t index)
@Constructor也可以,但我假设他需要函数中的
t
。我想您可以使用
ContainerType::value\u type
来实现这一点。。。哦well@Constructor:嗯,我没有想到。这也很好,因为在我的特定情况下,我实际上不需要
t