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?
Asked
Active
Viewed 1,735 times
6

DejaVu
- 155
- 10
-
1Explicit `inline` might help for definition. – πάντα ῥεῖ Jan 29 '15 at 23:00
-
possible duplicate of [How to have static data members in a header-only library?](http://stackoverflow.com/questions/11709859/how-to-have-static-data-members-in-a-header-only-library) – danielschemmel Jan 29 '15 at 23:05
1 Answers
12
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 anenum
type.Other type, logically constant:
Use a C++11constexpr
.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.

Cheers and hth. - Alf
- 142,714
- 15
- 209
- 331