简体   繁体   中英

Using compound literals in C++

I would like to initialize a variable of type Matrix4 with a compound literal . My constructor expects a float* .

So here is my line of initialization:

const Matrix4 Matrix4::identity ( (float[16]) { 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f } );

This seems like it should work, but Visual Studio says it's "non standard explicit type conversion". But I would like to keep the "one-line initialization", except if there really is a more convenient way.

You have overcomplicated the question with irrelevant static member detail. In fact, the question can be easily reproduced as:

void foo(float* );

void k() {
    foo((float[4]){1, 2, 3, 4});
}

What you have here is a 'compound literal', defined for C99. It is not available in C++ by standard, but some compilers have extensions which support this. From the question itself, it seems like MSVC also supports this extension - it mentions this in the message - but doesn't allow the code. Probably there is a way to explicitly enable it on MSVC, but I am not expert on this.

I do not really see a reason to write non-conformant code in this case, so I would advocate against it.

Answering the question after edit, there are really several ways how one can achieve a single-line call. One could make function to accept std::initializer_list<float> for variable number of arguments, std::array<float, 16> for fixed number of arguments, or gsl::span .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM