Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

"unnamed", "anonymous" array in C++

55 views
Skip to first unread message

jono...@googlemail.com

unread,
Mar 19, 2015, 7:08:36 PM3/19/15
to
Hi,

look at this:

////////////////////////////
#include <iostream>

using namespace std;

template<size_t len>
void print(const char * const(&arr_str)[len])
{
for (size_t i = 0; i < len; ++i) {
cout << arr_str[i] << '\n';
}
}

int main()
{
const char word1[] = "C++";
const char word2[] = "is";
const char word3[] = "great";

print((const char* const []){word1, word2, word3});

return 0;
}
////////////////////////////////////////////////

(It's 100% legal in C++, right?)

Could it be written in a more idiomatic way, or is it already ok?


Thanks.
J.

jono...@googlemail.com

unread,
Mar 19, 2015, 7:13:05 PM3/19/15
to
Ah one alternative (if one really wants to), would be to use std::array


//////////////////////////////
// c++11/14/17

#include <iostream>
#include <array>

using namespace std;

template<size_t N>
void print(const array<const char* const, N> &arr)
{
for (size_t i = 0; i < N; ++i) {
cout << arr[i] << '\n';
}
}

int main()
{
const char word1[] = "C++";
const char word2[] = "is";
const char word3[] = "great";

print(array<const char* const, 3>{{word1, word2, word3}});

return 0;
}
/////////////////////////////////////
Message has been deleted

Richard

unread,
Mar 23, 2015, 4:40:06 PM3/23/15
to
[Please do not mail me a copy of your followup]

r...@zedat.fu-berlin.de (Stefan Ram) spake the secret code
<compound-literal...@ram.dialup.fu-berlin.de> thusly:

>jono...@googlemail.com writes:
>>print((const char* const []){word1, word2, word3});
>
> Compound literals are not part of C++ IIRC.

It's a C++11 initializer list.
--
"The Direct3D Graphics Pipeline" free book <http://tinyurl.com/d3d-pipeline>
The Computer Graphics Museum <http://computergraphicsmuseum.org>
The Terminals Wiki <http://terminals.classiccmp.org>
Legalize Adulthood! (my blog) <http://legalizeadulthood.wordpress.com>
0 new messages