[英]Using compound literals in C++
I would like to initialize a variable of type Matrix4
with a compound literal
. 我想使用
compound literal
初始化Matrix4
类型的变量。 My constructor expects a float*
. 我的构造函数期望
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". 这似乎应该起作用,但是Visual Studio表示它是“非标准显式类型转换”。 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. 您在这里拥有的是为C99定义的“复合文字”。 It is not available in C++ by standard, but some compilers have extensions which support this.
按照标准,它在C ++中不可用,但是某些编译器具有支持此功能的扩展。 From the question itself, it seems like MSVC also supports this extension - it mentions this in the message - but doesn't allow the code.
从问题本身来看,MSVC似乎也支持此扩展-它在消息中提到了此扩展-但不允许使用代码。 Probably there is a way to explicitly enable it on MSVC, but I am not expert on this.
可能有一种方法可以在MSVC上显式启用它,但是我对此并不熟练。
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
. 可以使函数接受
std::initializer_list<float>
作为可变数量的参数, std::array<float, 16>
作为固定数量的参数,或者接受gsl::span
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.