How to have static data members in a header-only library?

后端 未结 3 971
走了就别回头了
走了就别回头了 2020-11-29 08:04

What is the best way to have a static member in a non-templated library class, without placing the burden of defining the member on the class user?

Say I want to pro

3条回答
  •  余生分开走
    2020-11-29 08:46

    My own solution is to use a templated holder class, as static members work fine in templates, and use this holder as a base class.

    template 
    struct static_holder
    {
        static T static_resource_;
    };
    
    template 
    T static_holder::static_resource_;
    

    Now use the holder class:

    class expensive_resource { /*...*/ };
    
    class i_want_a_static_member : private static_holder
    {
    public:
        void foo()
        {
            static_resource_.bar();
        }
    };
    

    But as the name of the member is specified in the holder class, you can't use the same holder for more than one static member.

提交回复
热议问题