How to initialize static members in the header

前端 未结 8 1154
伪装坚强ぢ
伪装坚强ぢ 2020-12-13 09:02

Given is a class with a static member.

class BaseClass
{
public:
    static std::string bstring;
};

String has obviously to be default-

8条回答
  •  被撕碎了的回忆
    2020-12-13 09:08

    Regarding

    Isn't there a way to define [the static data member] in the header?

    Yes there is.

    template< class Dummy >
    struct BaseClass_statics
    {
        static std::string bstring;
    };
    
    template< class Dummy >
    std::string BaseClass_statics::bstring = ".";
    
    class BaseClass
        : public BaseClass_statics
    {};
    

    An alternative is to use a function, as Dietmar suggested. Essentially that is a Meyers' singleton (google it).

    Edit: Also, since this answer was posted we've got the inline object proposal, which I think is accepted for C++17.

    Anyway, think twice about the design here. Globals variables are Evil™. This is essentially a global.

提交回复
热议问题