How does std::array initializer work for char's?
I'm not sure how the following code works. I thought you had to do {'h', 'e' ...etc...}
but it seems to work fine. On the other hand if you do std::array<const char*
it only adds one element to the array. Are there special rules for string literal initialization?
std::array<char, strlen("hello world!") + 1> s = {"hello world!"};
for (size_t i = 0; i < s.size(); ++i)
{
std::cout << s[i];
}
Class std::array
is an aggregate. In this statement:
std::array<char, strlen("hello world!") + 1> s = {"hello world!"};
list initialization is used. As the first and only element of this instantiation of the class std::array
is a character array it may be initialized with string literals.
It would be more correctly to use sizeof
operator instead of function strlen
:
std::array<char, sizeof( "hello world!" )> s = {"hello world!"};
Also you could write
std::array<char, sizeof( "hello world!" )> s = { { "hello world!" } };
because the character array in turn is an aggregate.
According to the C++ Standard
8.5.2 Character arrays [dcl.init.string]
1 An array of narrow character type (3.9.1), char16_t array, char32_t array, or wchar_t array can be initialized by a narrow string literal, char16_t string literal, char32_t string literal, or wide string literal, respectively, or by an appropriately-typed string literal enclosed in braces (2.14.5). Successive characters of the value of the string literal initialize the elements of the array.
[ Example: char msg[] = "Syntax error on line %sn";
Here's a way of achieving this
// GOAL
std::array<char, sizeof("Hello")> myarray = {"Hello"};
ie. initializing std::array with a string literal (yes, it used a macro)
// SOLUTION
#define STD_CHAR_ARRAY_INIT(arrayname, string_literal) /*std::array*/<char, sizeof(string_literal)> arrayname = {string_literal}
std::array STD_CHAR_ARRAY_INIT(myarray, "Hello");
Here's some test code:
#include <iostream>
#include <array>
using std::cout;
using std::ostream;
template<typename T, size_t N>
std::ostream& std::operator<<(std::ostream& os, array<T, N> arr)
{
{
size_t cnt = 0;
char strchar[2] = "x";
for (const T& c : arr) {
strchar[0] = c;
os << "arr[" << cnt << "] = '" << (c == ' ' ? " " : strchar /*string(1, c)*/ ) << "'n"
<< '.' << c << '.' << 'n';
++cnt;
}
}
return os;
}
#define STD_CHAR_ARRAY_INIT(arrayname, string_literal) /*std::array*/<char, sizeof(string_literal)> arrayname = {string_literal}
int main()
{
std::array STD_CHAR_ARRAY_INIT(myarray, "Hello");
cout << myarray << 'n';
return 0;
}
链接地址: http://www.djcxy.com/p/81476.html