dimanche 23 octobre 2016

Casting an anonymous array initializer list

I can successfully do a C cast of an initializer list for an array of char strings, but can't seem to get it to work with a C++ cast (static_cast):

int main()
{
   char x[] = "test 123";

   // This works fine:

   char **foo = (char *[]) { "a", x, "abc" };
   std::cout << "[0]: " << foo[0] << "    [1]: " << foo[1]
             << "    [2]: " << foo[2] << std::endl;

   // This will not compile ("expected primary-expression before '{' token"):

   //char **bar = static_cast<char *[]>( { "a", x, "abc" } );
   //std::cout << "[0]: " << bar[0] << "    [1]: " << bar[1]
   //          << "    [2]: " << bar[2] << std::endl;
}

Is it possible to use a C++ cast here? If so, what's the correct syntax? If not, why not, and is the C cast letting me get away with something I shouldn't be doing?

Ultimately, the reason I'm asking this is that I am calling a function that has a char array pointer as a parameter, and I would like to use an anonymous array as the calling argument.

I'm using GCC 4.4.6.

Aucun commentaire:

Enregistrer un commentaire