c++ - How to convert std::array to a class type -
i have below code need create array of object thru templated class. templated class receive class 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 : 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]; (int = 0 ; < anotherclass::mysize; i++) { objtemp[i] = new anotherclass(2); } return objtemp; } //a<b> obj[256] = [] () {for (int = 0 ; < 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 getting below error -
could not convert ‘objtemp’ ‘a<b> [256]’ ‘std::array<b, 256ul> conversion ‘std::array<b, 256ul>’ non-scalar type ‘a<b>’ requested
i changed objtemp std::array , error went away below error -
32:1 error: need ‘typename’ before ‘a<anotherclass>::obj’ because ‘a<anotherclass>’ dependent scope a<anotherclass>::obj = a<anotherclass>::init();
i not sure error means?
i got actual fix:
template <typename anotherclass> anotherclass a<anotherclass>::obj[anotherclass:: mysize] = a<anotherclass>::init();
but below output receive :
b called called
whereby expecting b' constructor called 256 times cause of below statement
objtemp[i] = new anotherclass(2)
i understand since need create 256 objects of class b type constructor should called 256 times not happening in case. should initialise static array of objects in case -
template <typename anotherclass> anotherclass a<anotherclass>::obj[anotherclass:: mysize] = a<anotherclass>::init();
whats wrong in above code or missing something?
just make mind whether you're going use c-style array or std::array
. latter seems better choice, c-style arrays can't copied simply you're using c++ (11).
so declare objtemp
, obj
std::array
s.
Comments
Post a Comment