Casting an anonymous array initializer list

余生颓废 提交于 2019-12-24 00:53:21

问题


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.


回答1:


I can successfully do a C cast of an initializer list for an array of char strings

No, you can't. You didn't use an initializer list nor a C cast at all. What you used was a compound literal. It is a C language feature that doesn't exist in C++. Some compilers do support them in C++ as a language extension.

I highly recommend you to use a compiler option that at least warns when you use non-standard features to avoid confusion like this.

but can't seem to get it to work with a C++ cast

You cannot cast an initializer list expression. You will have to initialize a named array normally, then the pointer - although you hardly ever really need a separate pointer variable since the array implicitly decays to a pointer in most contexts anyway.

const char* arr[] = { "a", x, "abc" };
const char** foo = arr;

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.

If you can modify the function, then there are ways to allow the call without a named array. You could accept an std::initializer_list, or a type that can be constructed from an initializer list such as an instance of std::array.


PS. Implicit conversion from string literal to char* is not allowed in C++ either - but allowed by some compilers as a language extension. Use const char* here.



来源:https://stackoverflow.com/questions/40210524/casting-an-anonymous-array-initializer-list

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!