今天,我認爲這將是一個不錯的主意,超載operator<<
對於C風格的數組:重載運算符<<數組
template<typename T, size_t N>
std::ostream& operator<<(std::ostream& os, T(&a)[N])
{
os << '{' << a[0];
for (size_t i = 1; i < N; ++i)
{
os << ',' << ' ' << a[i];
}
os << '}';
return os;
}
int main()
{
int numbers[] = {2, 3, 5, 7, 11, 13, 17, 19};
std::cout << numbers << '\n';
}
事實上,這很好地打印{2, 3, 5, 7, 11, 13, 17, 19}
。但是,通過提供超載,我不能再打印字符串文字:
std::cout << "hello world\n";
error: ambiguous overload for 'operator<<' in 'std::cout << "hello world\012"'
note: candidates are:
note: std::basic_ostream<_CharT, _Traits>::__ostream_type&
std::basic_ostream<_CharT, _Traits>::operator<<(long int) [with _CharT = char, _
Traits = std::char_traits<char>, std::basic_ostream<_CharT, _Traits>::__ostream_
type = std::basic_ostream<char>] <near match>
note: no known conversion for argument 1 from 'const char [13]' to 'long int'
這真是令人費解。爲什麼編譯器甚至在沒有從const char[13]
到long int
首先轉換的情況下考慮過載long int
?此錯誤消息的
變化出現long unsigned int
,short int
,short unsigned int
,int
,unsigned int
,long long int
和long long unsigned int
。
(其他候選人是const void*
,const char*
和const _CharT*
,和我自己的模板。)
我提供了唯一的非字符類型的模板解決了這個問題:
template<typename T, size_t N>
typename std::enable_if<
!std::is_same<typename std::remove_cv<T>::type, char>::value,
std::ostream&>::type operator<<(std::ostream& os, T(&a)[N])
但我仍然對編譯器將數字類型視爲候選者的問題感到困惑。
'std :: ostream'是對類的引用。 – Mankarse 2012-01-29 11:04:41