Static member in header-only library

前端 未结 1 936
情歌与酒
情歌与酒 2021-02-09 20:03

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?

相关标签:
1条回答
  • 2021-02-09 20:11

    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:
      Give it a value in the declaration in the class definition. Or you might use an enum type.

    • Other type, logically constant:
      Use a C++11 constexpr.

    • Not necessarily constant, or you can't use constexpr:
      Use the templated static trick, or a Meyers' singleton.

    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.

    0 讨论(0)
提交回复
热议问题