c++ - Output a C array through ostream -
i'm trying output c array using iostream.
for array of ints, wrote code this
template <size_t n> ostream& operator<< (ostream& os, const int (&x)[n]) { for(int i=0; i<n; i++) os<<x[i]<<","; return os; } int main() { int arr[]={1,2,3}; cout<<arr<<endl; return 0; }
and works pretty fine.
then, i'd generalize more types (like chars, floats etc), update original version follows
template <class t, size_t n> ostream& operator<< (ostream& os, const t (&x)[n]) { for(int i=0; i<n; i++) os<<x[i]<<","; return os; }
the main function didn't change, however, time, when compile it, error occured.
in function `std::ostream& operator<<(std::ostream&, const t (&)[n]) [with t = int, long unsigned int n = 3ul]': a.cpp:15: instantiated here a.cpp:9: error: ambiguous overload `operator<<' in `(+os)->std::basic_ostream<_chart, _traits>::operator<< [with _chart = char, _traits = std::char_traits<char>]((*((+(((long unsigned int)i) * 4ul)) + ((const int*)x)))) << ","' /usr/lib/gcc/x86_64-redhat-linux/3.4.5/../../../../include/c++/3.4.5/bits/ostream.tcc:121: note: candidates are: std::basic_ostream<_chart, _traits>& std::basic_ostream<_chart, _traits>::operator<<(long int) [with _chart = char, _traits = std::char_traits<char>] <near match> /usr/lib/gcc/x86_64-redhat-linux/3.4.5/../../../../include/c++/3.4.5/bits/ostream.tcc:155: note: std::basic_ostream<_chart, _traits>& std::basic_ostream<_chart, _traits>::operator<<(long unsigned int) [with _chart = char, _traits = std::char_traits<char>] <near match> /usr/lib/gcc/x86_64-redhat-linux/3.4.5/../../../../include/c++/3.4.5/bits/ostream.tcc:98: note: std::basic_ostream<_chart, _traits>& std::basic_ostream<_chart, _traits>::operator<<(bool) [with _chart = char, _traits = std::char_traits<char>]
how can fix this? thank suggestions.
there exists overload operator << (const char*)
ambiguous template.
you may restrict template sfinae exclude char
:
template <class t, size_t n, typename = typename std::enable_if<!std::is_same<char, t>::value>::type> ostream& operator<< (ostream& os, const t (&x)[n])
Comments
Post a Comment