Increase the compile-time variable with each instance of the generic class

I have this class:

template <typename T, uint64_t N>
struct Probe {
  static const uint64_t Counter = N;
  typedef T Type;
};

I use like:

typedef Probe <int, 0> FirstIntProbe;
typedef Probe <int, 1> SecondIntProbe;
typedef Probe <float, 2> FloatProbe;

Is it possible to create a time \ macro compilation method that allows me to instantiate this class without specifying a second parameter, for example:

typedef Probe <int, Something?> FirstIntProbe;
typedef Probe <int, Something?> SecondIntProbe;
typedef Probe <float, Something?> FloatProbe;

I suppose this is not possible, but again I saw people doing something in C ++. I would not think that this is possible earlier.


Update:

  • There is no need to increase by one, it is simply important that each probe has its own number.
  • No need to have a unique number in different .cpp files \ translation units.
+5
source share
3 answers

__COUNTER__, ( GCC MSVC, ). , __COUNTER__ , .. .cpp.

edit: . ( GCC 4.5):

probe.h:

template <typename T, int N>
struct Probe {
    typedef T Type;
};

#define DECLARE_PROBE(type) typedef struct Probe<type, __COUNTER__>

main.cpp:

#include "test.h"

DECLARE_PROBE(int) intprobe;
DECLARE_PROBE(float) floatprobe;

int main(int argc, char** argv) {
    intprobe ip;
    floatprobe fp;
    return 0;
}

test.cpp:

#include "test.h"

DECLARE_PROBE(int) intprobe;
DECLARE_PROBE(float) floatprobe;

static intprobe ip;
static floatprobe fp;
+7

, (.. Counter ): ( ), , . - :

int currentProbeCounter;

template <typename T>
struct Probe
{
    static int const counter;
    //  ...
};

template <typename T>
const int Probe<T>::counter = ++ currentProbeCounter;

, Probe<T>::counter , ( ) ; Probe ( ) . ( , , , .)

+5

All Articles