Mina Ashraf
Mina Ashraf

Reputation: 353

Why do variadic templates behave like this in c++?

I need help understanding this piece of code. There are no loops available, so how can the template, which I know is processed at compilation time, fetch all the arguments, and why did it call the same variable "c" which was incremented even though it is only in the specialized "Z" version ?

#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>

using namespace std;

class Z
{
    Z() {}
    virtual ~Z() {}
};

class A
{
    A() {}
    virtual ~A() {}
};

class B
{
    B() {}
    virtual ~B() {}
};

template <class P, class... args>
class TCount : public TCount<args...>
{
public:
    TCount() : TCount<args...>() { this->c++; }
    virtual ~TCount() {}
};

template <>
class TCount<Z>
{
protected:
    int c;

public:
    TCount() { c = 0; }
    int getC() { return c; }
    virtual ~TCount() {}
};

int main()
{
    TCount<A, B, A, B, Z> tCount;
    cout << tCount.getC() << endl;
    return 0;
}

Upvotes: 3

Views: 122

Answers (1)

max66
max66

Reputation: 66230

The trick is in the recursion of the class definition.

I mean... when you define

TCount <A,B,A,B,Z> tCount;

you have that

  • TCount<A,B,A,B,Z> inherits from TCount<B,A,B,Z>
  • TCount<B,A,B,Z> inherits from TCount<A,B,Z>
  • TCount<A,B,Z> inherits from TCount<B,Z>
  • TCount<B,Z> inherits from TCount<Z>
  • TCount<Z> define c and initialize it to zero
  • TCount<B,Z> inherit c and, in body constructor, increment it (c become 1)
  • TCount<A,B,Z> inherit c and, in body constructor, increment it (c become 2)
  • TCount<B,A,B,Z> inherit c and, in body constructor, increment it (c become 3)
  • TCount<A,B,A,B,Z> inherit c and, in body constructor, increment it (c become 4)

Upvotes: 4

Related Questions