dimanche 20 août 2017

How to convert std::array to a class type

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 <class 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 <class anotherclass>
std::array<anotherclass, anotherclass::mysize> A<anotherclass>::init ()
{
    A<anotherclass> 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)}};
A<B> obj[256] = A<B>::init();

int main()
{
    A<B> a;
}

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

Though there are other errors also but I believe if I fix this one I can get rid of others?

Aucun commentaire:

Enregistrer un commentaire