這工作,但並不安全不會被意外調用標準char*
版operator<<
:
#include <iostream>
template <unsigned N>
std::ostream& operator<< (std::ostream& out, const char (& data) [N])
{
out.write (data, N);
// or out.write (data, strnlen (data, N));
// if you want to stop at a '\0' in the data
return out;
}
struct Foo {
char one[5];
char two[1];
char three[5];
};
int main (void)
{
using namespace std;
Foo foo = {
{ 'h', 'e', 'l', 'l', 'o' },
{ ' ' },
{'w', 'o', 'r', 'l', 'd'} };
cout << foo.one;
cout << foo.two;
cout << foo.three;
cout << endl;
}
這是更安全,使用maxw
型這限制了下一個char*
輸出的長度:
struct maxw {
unsigned n;
maxw (unsigned n) : n (n) { }
};
struct maxw_stream {
std::ostream& stream;
unsigned n;
maxw_stream (std::ostream& stream, unsigned n) :
stream (stream),
n (n) {
}
};
maxw_stream operator<< (std::ostream& out, const maxw& m)
{
return maxw_stream (out, m.n);
}
std::ostream& operator<< (const maxw_stream& out, const char* data)
{
out.stream.write (data, strnlen (data, out.n));
return out.stream;
}
// eg:
cout << maxw(4) << "Hello World!" << endl;
// Hell\n
cout << maxw(100) << "Hello World!" << endl;
// Hello World!\n
在你的第二個調用中,整個第二個參數只是簡單的調用普通的'strlen'。但是在這種情況下,你可能只是使用整個語句的更習慣的方式:'stream << buffer'。 – 2009-10-09 07:54:27
編號strlen在最大字節後不會停止。 – 2009-10-09 08:04:17
'strnlen'會。 strnlen調用看起來更清晰:'strnlen(buffer,maxbytes)'。不要使用指針或任何東西 – gnud 2009-10-09 08:33:27