I'd like to have your opinion on how to emulate variable template as a class member. That is having a data member in your class that is dependent on a template, but not on a class template. Conceptually, something that could be written as :
class M
{
private:
template<typename T>
SomethingThatCouldDependOnT<T> m_dataMember;
};
My first thought was to make something like this :
#include <iostream>
class A
{
public :
template<typename T>
void myMethod()
{
static int a = 0;
std::cout << "my method : " << a << " calls" << std::endl;
a++;
}
};
int main()
{
A a, b;
a.myMethod<int>();
a.myMethod<int>();
a.myMethod<double>();
b.myMethod<double>();
return 0;
}
But this doesn't work because the static member in myMethod isn't per instance but per method generated. Actually, it makes sense as myMethod can be seen as a global function taking as first parameter an object of type A (without taking account the visibility concerns). So i came up with an other idea :
#include <iostream>
#include <vector>
class A
{
public :
A() : i(-1) {}
template<typename T>
void myMethod()
{
static std::vector<int> a;
static int max = 0;
if(i < 0)
{
i = max;
a.push_back(0);
max++;
}
std::cout << "my method : " << a[i] << " calls" << std::endl;
a[i]++;
}
private:
int i;
};
int main()
{
A a, b;
a.myMethod<int>();
a.myMethod<int>();
a.myMethod<double>();
b.myMethod<double>();
return 0;
}
But I don't really like it, even if it could be improved by reusing integers unused or using a more appropriate container.
I want to think that it might have a better solution for my problem here, that's why i'm asking.