简体   繁体   English

标头库中的静态成员

[英]Static member in header-only library

I'm creating header-only library and I have to use static member. 我正在创建仅限标头的库,我必须使用静态成员。
Is it possible to define it in the header file without redefinition warning? 是否可以在头文件中定义它而不重新定义警告?

Assuming you're talking about a static data member, since a static function member is no problem, there are various techniques for different cases: 假设您正在谈论静态数据成员,因为静态函数成员没有问题,针对不同情况有各种技术:

  • Simple integral type, const , address not taken: 简单的整数类型, const ,地址未采取:
    Give it a value in the declaration in the class definition. 在类定义的声明中为它赋值。 Or you might use an enum type. 或者您可以使用enum类型。

  • Other type, logically constant: 其他类型,逻辑上不变:
    Use a C++11 constexpr . 使用C ++ 11 constexpr

  • Not necessarily constant, or you can't use constexpr : 不一定是常数,或者你不能使用constexpr
    Use the templated static trick, or a Meyers' singleton. 使用模板化的静态技巧或Meyers的单例。

Example of Meyers' singleton: 迈耶斯单身人士的例子:

class Foo
{
private:
    static
    auto n_instances()
        -> int&
    {
         static int the_value;
         return the_value;
    }
public:
    ~Foo() { --n_instances(); }
    Foo() { ++n_instances(); }
    Foo( Foo const& ) { ++n_instances(); }
};

Example of the templated statics trick: 模板化静态技巧的示例:

template< class Dummy >
struct Foo_statics
{
    static int n_instances;
};

template< class Dummy >
int Foo_statics<Dummy>::n_instances;

class Foo
    : private Foo_statics<void>
{
public:
    ~Foo() { --n_instances; }
    Foo() { ++n_instances; }
    Foo( Foo const& ) { ++n_instances; }
};

Disclaimer: no code touched by a compiler. 免责声明:编译器没有触及任何代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM