[英]How can I initialize class variables in a header?
I'm writing a library where the user can define arbitrary structures and pass them to my library, which will then obtain the memory layout of the structure from a static member such structure must have as a convention. 我正在编写一个库,用户可以在其中定义任意结构并将其传递给我的库,该库随后将从静态成员获得该结构必须具有的约定的结构的内存布局。
For example: 例如:
struct CubeVertex {
// This is, per convention, required in each structure to describe itself
static const VertexElement Elements[];
float x, y, z;
float u, v;
};
const VertexElement CubeVertex::Elements[] = {
VertexElement("Position", VertexElementType::Float3),
VertexElement("TextureCoordinates", VertexElementType::Float2),
};
C++ best practices would suggest that I move the static variable and its initialization into my source (.cpp) file. C ++最佳实践建议我将静态变量及其初始化移到我的源(.cpp)文件中。 I, however, want to keep the variable initialization as close to the structure as possible since whenever the structure changes, the variable has to be updated as well. 但是,我想使变量初始化尽可能地靠近结构,因为每当结构更改时,变量也必须更新。
Is there a portable ( = MSVC + GCC at least ) way to declare such a variable inside the header file without causing ambiguous symbol / redefinition errors from the linker? 有没有一种可移植的( 至少= MSVC + GCC )方式在头文件中声明这样的变量,而不会引起链接器的符号错误/重新定义错误?
What you could do here is using an anonymous namespace. 您可以在这里使用匿名名称空间。
Wrap everything into "namespace { ... };" 将所有内容包装到“命名空间{...};”中 and you can then access CubeVertex::Elements like you normally do. 然后您可以像平常一样访问CubeVertex :: Elements。
However, this creates a new instance of the static data everytime you include the headerfile, which adds to the executable's filesize. 但是,每次包含头文件时,这都会创建一个静态数据的新实例,这会增加可执行文件的文件大小。
It also has some limitations on how to use the class/struct, because you cannot call functions of that class from another file (which won't be a problem in this special case here). 它还对如何使用类/结构有一些限制,因为您不能从另一个文件调用该类的函数(在此特殊情况下,这将不是问题)。
Consider a simple getter. 考虑一个简单的吸气剂。
struct CubeVertex {
static const std::array<VertexElement, N>& GetElements() {
static const std::array<VertexElement, N> result = {
//..
};
return result;
}
//..
}
Immediate benefit: No array-to-pointer-decay. 直接收益:没有数组到指针的衰减。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.