5

Let's say we have the following class:

class A {
    static SomeLongType b;
};

Now we have to initialize it in the appropriate cpp file. I can think of the following ways:

SomeLongType A::b{}; // repetition of SomeLongType
decltype(A::b) A::b{}; // A::b written two times

Both seem to be kind of cumbersome to me. Is there a better way?

John Dibling
  • 99,718
  • 31
  • 186
  • 324
Appleshell
  • 7,088
  • 6
  • 47
  • 96
  • Just carping: You miss `public::` in the class `A`. :) – herohuyongtao Jan 24 '14 at 18:17
  • If the type is of an integer or enumeration type, it can be initialized in the class declaration (in C++11). Otherwise, no, you have to initialize it in the implementation (much like member functions that are not implemented in the class declaration). – Zac Howland Jan 24 '14 at 18:20
  • Try to use template class with static variable type as parameter. – PiotrNycz Jan 24 '14 at 18:22
  • 2
    It'd be nice to use `auto`, but see http://stackoverflow.com/questions/14285198/why-doesnt-the-c11-auto-keyword-work-for-static-members?rq=1 – ecatmur Jan 24 '14 at 18:24
  • 1
    @herohuyongtao Nope, b can be private. But `static` variables need an definition. – harper Jan 24 '14 at 18:29
  • Since you are using `decltype` can we assume C++11? I've edited the tags. – John Dibling Jan 24 '14 at 18:46

1 Answers1

3

The perfect solution would be to use C++11 auto. But as ecatmur commented, thats not allowed by the language.

Why not just define a simple macro?

#define DEFINE(x) decltype(x) x{}

struct A
{
    static SomeLongType b;
};

DEFINE( A::b );

I really hate C macros, but they are usefull in certain cases.

Manu343726
  • 13,969
  • 4
  • 40
  • 75
  • And for bonus points, you can make it a [variadic macro](http://gcc.gnu.org/onlinedocs/cpp/Variadic-Macros.html) to take care of more complicated constructors. Not sure how portable that syntax is, though... – Xavier Holt Jan 24 '14 at 18:58
  • 2
    @XavierHolt: Variadic macros are allowed in c++11. – Alexandre C. Jan 24 '14 at 19:49
  • 2
    @XavierHolt or just define the macro as `#define DEFINE(x) decltype(x) x`, using it as `DEFINE(A::b);`, or `DEFINE(A::b){ some params here };`, or `DEFINE(A::b) = something;`. I think its more clear than `#define DEFINE(X , params...)` `DEFINE(A::b , p1 , p2 , p3, etc )`, and its less tricky and more flexible. – Manu343726 Jan 25 '14 at 10:53