I have the below code where I need to create an array of object thru a templated class. The templated class will receive another class as its type:
#include <iostream>
#include <array>
class B
{
public:
B() {std::cout << "B Called" <<std::endl;}
B(int y){std::cout << "B int Called" <<std::endl;}
static const int mysize;
};
const int B::mysize = 256;
template <typename anotherclass>
class A : public anotherclass
{
public:
A(){std::cout << "Called" << std::endl;}
static anotherclass* obj[anotherclass::mysize];
//static anotherclass[] init();
static std::array<anotherclass*,anotherclass::mysize> init();
};
template <typename anotherclass>
std::array<anotherclass*, anotherclass::mysize> A<anotherclass>::init ()
{
std::array<anotherclass*,256> objtemp[anotherclass::mysize];
for (int i = 0 ; i < anotherclass::mysize; i++)
{ objtemp[i] = new anotherclass(2); }
return objtemp;
}
//A<B> obj[256] = [] () {for (int i = 0 ; i < 256; i++) { obj[i] = new A<B>(2)}};
template <typename anotherclass>
anotherclass* A<anotherclass>::obj[anotherclass:: mysize] = A<anotherclass>::init();
int main()
{
A<B> a;
}
When I am constantly getting below error -
could not convert ‘objtemp’ from ‘A<B> [256]’ to ‘std::array<B, 256ul>
conversion from ‘std::array<B, 256ul>’ to non-scalar type ‘A<B>’ requested
I changed the objtemp as an std::array and error went away but I get below error -
32:1 error: need ‘typename’ before ‘A<anotherclass>::obj’ because ‘A<anotherclass>’ is a dependent scope
A<anotherclass>::obj = A<anotherclass>::init();
I am not sure what this error means?
I got the actual fix:
template <typename anotherclass>
anotherclass A<anotherclass>::obj[anotherclass:: mysize] = A<anotherclass>::init();
But below is the output I receive :
B Called
Called
Whereby I was expecting B' constructor to be called 256 times cause of below statement
objtemp[i] = new anotherclass(2)
I understand that since I need to create 256 objects of class B type its constructor should be called 256 times which is not happening in my case. So what should I do to initialise a static array of objects in my case -
template <typename anotherclass>
anotherclass A<anotherclass>::obj[anotherclass:: mysize] = A<anotherclass>::init();
Whats the wrong in above code or I am missing something?