编译错误C++模板化函数,迭代器作为arugments

use*_*585 0 c++ templates

我以为我开始掌握C++了......

然后我写了我认为我们非常简单的模板化函数,突然间它似乎再没有任何意义.编译器似乎甚至不喜欢我已定义模板化函数的事实,这看起来有点疯狂.它是单个编译单元,所以我不确定它会抱怨什么.

#include <vector>
#include <iostream>

typedef std::vector<int> int_vec_type;

template <typename Type>
bool print_vec(Type::const_iterator itr, const Type::const_iterator end)
{
    for (; itr != end; ++itr) {
        std::cout << *itr << std::endl;
    }

    return true;
}

int
main()
{
    int_vec_type ivec;

    ivec.push_back(0);
    ivec.push_back(1);
    ivec.push_back(2);

    print_vec(ivec.begin(), ivec.end());

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

这些是编译错误:

tia.cc:7:22:错误:'bool print_vec'的模板声明

tia.cc:7:37:错误:预期')'在'itr'之前

tia.cc:7:42:错误:在'const'之前预期的primary-expression

tia.cc:在函数'int main()'中:

tia.cc:25:39:错误:'print_vec'未在此范围内声明

提前致谢.

Dav*_*eas 6

容器的类型不能从迭代器的类型中推断出来.您只需将模板转换为:

template <typename Iterator>
bool print_vec(Iterator itr, const Iterator end)
{
    for (; itr != end; ++itr) {
        std::cout << *itr << std::endl;
    }

    return true;
}
Run Code Online (Sandbox Code Playgroud)