函数模板编译错误

Function template compilation error

本文关键字:错误 编译 函数模板      更新时间:2023-10-16

以下代码

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

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

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

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

您的代码有两个问题。首先,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();
}

现场演示

我把模板模板形参改成可变的,因为标准库中的容器都有多个模板形参。


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

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

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

您需要typename关键字任何时候您有一个依赖类型(如ContainerType<T>::iterator):

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