相关疑难解决方法(0)

模板函数中的输出向量<T>

这一段代码报错:

template <class T>
void print_vector(vector<T>& v, string sep)
{
    std::ostream_iterator<T> ostr_it(std::cout, sep) ;
    std::copy(begin(v), end(v), ostr_it);
}
Run Code Online (Sandbox Code Playgroud)

main.cpp:17:30: 错误:没有匹配的构造函数来初始化 'std::ostream_iterator<float>' std::ostream_iterator<T> ostr_it(std::cout, sep);

我很困惑,因为如果我在模板函数之外执行此操作并直接输出向量,则不会出现错误:

vector<float> result(elements);
std::copy(begin(result), end(result), ostream_iterator<float>(cout, ", "));
Run Code Online (Sandbox Code Playgroud)

怎么了?我需要专门化每个模板函数吗?

c++ c++11

5
推荐指数
1
解决办法
223
查看次数

标签 统计

c++ ×1

c++11 ×1