这一段代码报错:
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)
怎么了?我需要专门化每个模板函数吗?
由于没有发布答案,我想我会继续。
Accept的签名ostream_iterator是 C 字符串,而不是 C++ 字符串:
std::ostream_iterator(ostream_type& stream, const CharT* delim)
Run Code Online (Sandbox Code Playgroud)
正如此处所述,已选择隐式转换为char *fromstd::string是不可取的,因此您会收到错误。
为了让它工作,你可以简单地std::string自己投射:
std::ostream_iterator<T> ostr_it(std::cout, sep); // DOES NOT WORK
std::ostream_iterator<T> ostr_it(std::cout, sep.c_str()); // WORKS
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
223 次 |
| 最近记录: |