C++: Header-only project, static const non-integral

后端 未结 1 871
既然无缘
既然无缘 2021-01-18 16:17

I have a header-only project. Inside it I have a class. Inside it (or anywhere else actually) I would like to have constant data (enum values to string and

相关标签:
1条回答
  • 2021-01-18 16:30

    The simpler is

    static T& global_t()
    { static T z = initializer; return z; }
    

    global_t() can be used whereve a T value is required.

    NOTE: In answer to rioki comment, we must also specify the function as inline if it is at global or namespace level (to avoid the "multiple instances" problem towards the linker).

    The inline keyword is not necessary if the function is a template or is a class member-function (for which the inline definition is by default)

    If the static T instantiation must be shared among different OS modules (read: DLLs) rioki is perfectly right, but -at that point- a header-only library makes no more sense.


    Starting from C++17, the inline specifier can also be used on variables.

    So, from C++17 onward, you can just write

    inline T global_object = initializer;
    

    You can also use inline for static members of function, to provide inline initialization, like

    class Class
    {
        static inline Type static_object_name = initializer;
    };
    
    0 讨论(0)
提交回复
热议问题