c++ - 声明函数模板的语法

标签 c++ templates containers

我正在尝试创建一个模板函数,它接受任何类型 T 的 vector 参数(目前是原始类型)并打印出其内容:

template<class T>
void displayContents(const vector<T>& data)
{
    vector<T>::const_iterator i;
    i=data.begin();

    for( ; i!=data.end(); i++){
        cout<<*i<endl;
    }
}

错误信息是:

In function 'void displayContents(const std::vector >&)': error: expected ';' before 'i' | error:'i' was not declared in this scope === Build finished: 2 errors, 0 warnings ===

我是否忽略了语法错误?

最佳答案

尝试以下操作:

  typename vector<T>::const_iterator i;

正如 Björn 已经在评论中指出的那样,它是必需的,因为它是模板的从属名称。

关于c++ - 声明函数模板的语法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8471511/

相关文章:

c++11 - 为什么我需要两次将迭代器解引用到智能指针而不是使用 operator->()?

java - 如何从整体部署中拆分 docker 文件

c++ - 使用智能指针实现容器

c++ - C++ Protobuf添加一个已经分配的重复数字字段

c++ - 流式传输 Boost.Serialization 文件

C++模板类编译错误

c++ - 如何协调将 header /源代码与模板分离的 C++ 习惯用法?

c++ - 如何在托管 dll 中重新初始化 native 代码

c++ - 模板类的模板化相等运算符不编译

javascript - flatiron.js/plates - 如何使用模板和 i18n?