Bar
Bar

Reputation: 23

Static member in a template class. Same counter for all types of the class

I just want to access the static member of a template class. I know how to initialize it, but my problem is printing it for all types and not just for one type at a time.

The relevant parts of my code:

#include <iostream>
using namespace std;
template <class T>
class SortArr
{
private:
    T* arr;
    int size;
    static int count;
    static int sum;
public:
void print_static()const
}
//the print function
template <class T>
void SortArr<T>::print_static()const
{
    cout << count << endl;
    cout << sum << endl;
}
//count all the objects
//sum of all the araay sizes

template<class T>
int SortArr<T>::count = 0;
template<class T>
int SortArr<T>::sum = 0;

int main()
{
SortArr<int>print_static();//just integer num
}
//How should I approach static variables by considering all objects of all types?
count for example will count both the integer and double objects

Upvotes: 0

Views: 140

Answers (1)

463035818_is_not_an_ai
463035818_is_not_an_ai

Reputation: 122133

Each instantiation of SortArr gets its own set of static members, they are completely different types. If you want to have one counter for different types you can use a common base class:

struct Counter {
    static int count;
};
int Counter::count = 0;

template <typename T> 
class SortArr : Counter {
     // ...
};

For illustration, consider

#include <iostream>

template <size_t ID>
struct Counter {
    static int value;
};

template <size_t ID>
int Counter<ID>::value = 0;

int main() {
    Counter<0>::value = 24;
    Counter<42>::value = 123;
    std::cout << Counter<0>::value << ' ' << Counter<42>::value;
}

Output is 24 123, because each instantiation of Counter has its own value.

On the other hand, this

#include <iostream>

struct Counter {
    static int value;
};
int Counter::value = 0;

template <typename T>
struct Foo : Counter {
    using Counter::value;
};

int main() {
    Foo<int>::value = 42;
    Foo<double>::value = 123;
    std::cout << Foo<int>::value << ' ' << Foo<double>::value;
}

Has output 123 123, because all instantiations of Foo share the same counter.

Upvotes: 3

Related Questions