简体   繁体   中英

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. 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?

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.

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.

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