오늘은 C 스타일 배열에 대한 operator<<
에 과부하를 위해 좋은 생각이 될 것이라고 생각 : 오버로드 연산자 << 배열에 대한
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