问题描述
我想编写模板函数,该函数可以打印 std :: vector
,std :: list之类的容器。
I want to write template function which can print container like std::vector
, std::list.
下面是我的函数,只是重载<<
。
Below is my function, just overload <<
.
template<typename Container>
std::ostream& operator<<(std::ostream& out, const Container& c){
for(auto item:c){
out<<item;
}
return out;
}
测试代码如下:
int main(){
std::vector<int> iVec{5, 9, 1, 4, 6};
std::cout<<iVec<<std::endl;
return 0;
}
输出:
59146
我想在每个空格中添加一个空格值(输出类似于 5 9 1 4 6
),因此我将函数更改为:
And I want to add a space string in each value(output like 5 9 1 4 6
), so I change the function to:
template<typename Container>
std::ostream& operator<<(std::ostream& out, const Container& c){
for(auto item:c){
out<<item<<" ";
}
return out;
}
然后出现错误:
merror: ambiguous overload for 'operator<<' (operand types are 'std::basic_ostream<char>' and 'const char [2]')
out<<item<<" ";
我知道<<
可以输出
int a = 0;
double f = 0.3;
std::string s = "123";
std::cout<<a<<f<<s<<std::endl;
那么为什么会出现上述错误?并且有什么办法解决它?
So Why get the above error ? And is there any way to solve it?
我已经看到了这个问题中'operator<<'的重载,但我仍然不清楚。
I have see this question Ambiguous overload for ‘operator<<’ in ‘std::cout << but I still can't understand clearly.
所有代码:
#include <iostream>
#include <vector>
template<typename Container>
std::ostream& operator<<(std::ostream& out, const Container& c){
for(auto item:c){
out<<item;
// out<<item<<" "; // error
}
return out;
}
int main(){
std::vector<int> iVec{5, 9, 1, 4, 6};
std::cout<<iVec<<std::endl;
return 0;
}
推荐答案
声明 template< typename容器>
可能很危险,因为此模板包含所有变量类型 int
, char
等。由于此编译器不知道要使用哪个 operator<<
。
Declaring template<typename Container>
could be dangerous as this template includes 'all' variable types int
, char
etc. Due to this compiler does not know which operator<<
to use.
为了仅采用容器类型变量,请使用模板模板。
这是为您工作的代码
In order to take only container type variables use template of templates.Here is working code for you
template<typename T, template <typename, typename> class Container>
std::ostream& operator<<(std::ostream& out, const Container<T, std::allocator<T>>& c) {
for (auto item : c) {
out << item << " ";
}
return out;
}
int main()
{
cout << "Hello world" << endl;
int arr[] = { 0,3,6,7 };
vector<int> v(arr, arr+4);
cout << v << endl;
return 0;
}
这篇关于C ++打印模板容器错误(错误:“ operator<<”含糊不清的重载)理解?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!