输出向量T在模板功能中 [英] output vector<T> in template function

查看:83
本文介绍了输出向量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);
}




main.cpp:17:30:错误:没有用于初始化'std :: ostream_iterator< float>'
std :: ostream_iterator< T> ostr_it(std :: cout,sep);

main.cpp:17:30: error: no matching constructor for initialization of 'std::ostream_iterator<float>' std::ostream_iterator<T> ostr_it(std::cout, sep);

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

I am confused because if I do it outside the template function and output the vector directly there is no error:

vector<float> result(elements);
std::copy(begin(result), end(result), ostream_iterator<float>(cout, ", "));

怎么了?我需要专门化每个模板功能吗?

What is wrong? Do I need to specialize each template function?

推荐答案

由于没有答案,我想我会继续。

Since no answer was posted I guess I'll go ahead.

ostream_iterator 的签名接受的是C字符串,而不是C ++字符串:

The signature for ostream_iterator accept's a C-string, and not a C++ string:

std::ostream_iterator(ostream_type& stream, const CharT* delim)

已选择隐式转换 char * std :: string 是不可取的,如此处,所以会出现错误。

It has been chosen that implicit cast to char * from std::string is not desirable, as said here, so you get an error.

要使其正常工作,您可以简单地投射 std :: string 自己:

To make it work, you can simply cast the std::string yourself:

std::ostream_iterator<T> ostr_it(std::cout, sep);         // DOES NOT WORK
std::ostream_iterator<T> ostr_it(std::cout, sep.c_str()); // WORKS

这篇关于输出向量T在模板功能中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆