如何在仅标题库中拥有静态数据成员? [英] How to have static data members in a header-only library?

查看:270
本文介绍了如何在仅标题库中拥有静态数据成员?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在非模板化库类中有一个静态成员的最好方法是
,而不会给类用户定义成员的负担?



说我想要提供这个类:

  class i_want_a_static_member 
{
static expensive_resource static_resource_;

public:
void foo()
{
static_resource_.bar();
}
};

然后类的用户不能忘记定义静态成员
回答 许多 times ):

  //这必须在翻译单元中的某处
expensive_resource i_want_a_static_member :: static_resource_;

我有一个答案,但它有一些缺点。是否有更好和/或更优雅的解决方案?

解决方案

可以使用函数局部静态变量。

  struct Foo {
static int& Bar(){static int I;返回I; }
}; / / pre>

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 provide this class:

class i_want_a_static_member
{
    static expensive_resource static_resource_;

public:
    void foo()
    {
        static_resource_.bar();
    }
};

Then the user of the class must not forget to define the static member somewhere (as already answered many times):

// this must be done somewhere in a translation unit
expensive_resource i_want_a_static_member::static_resource_;

I do have an answer below, but it has some disadvantages. Are there better and/or more elegant solutions?

解决方案

You can use function local static variables.

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

这篇关于如何在仅标题库中拥有静态数据成员?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆