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

*爱你&永不变心* 提交于 2019-11-27 01:55:24

You can use function local static variables.

struct Foo {
     static int& Bar() { static int I; return I; }
}; //                    ^~~~~~~~~~~~

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 <typename T>
struct static_holder
{
    static T static_resource_;
};

template <typename T>
T static_holder<T>::static_resource_;

Now use the holder class:

class expensive_resource { /*...*/ };

class i_want_a_static_member : private static_holder<expensive_resource>
{
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.

As of C++ 17. You can now use inline variables to do this:

static const inline float foo = 1.25f;
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!