Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Static member in header-only library

Tags:

c++

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?

like image 454
DejaVu Avatar asked Jan 29 '15 22:01

DejaVu


1 Answers

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.

like image 143
Cheers and hth. - Alf Avatar answered Oct 24 '22 15:10

Cheers and hth. - Alf