c++ - How give random value for Template variable? -
c++ - How give random value for Template variable? -
i building matrix class , lets user specify type of info be. ie using template. want able assign random values each position in matrix based on template.
if template double , want double random value , , if int , want int random value. there way ?
code :
template <class t> void matrix<t>::randfill(t start , t end ){ std::srand(time(0)); for(size_t = 1; <= _rows ;i++){ for(size_t j = 1; j <= _cols l i++){ _matrix[(i-1)*_cols + (j-1)] = static_cast<t>(std::rand % (end - start) + 1) } } }
my question how can know template t @ runtime , alter result accordingly? there way switch statement matches type of template predefined types , gives appropriate values ? naive way set this, there feature in c++ ? know typeid operator, couldn't figure out how it. give me heuristic this? point me in right direction , rest.
on side note. in future want matrix class able take struct of 3 int s can represent rgb image. there way extract available info members in arbitrary struct or class ,and assign random value ?
sorry beingness verbose , wanted give clear thought of want do. -thank you.
just phone call function overloaded on each type:
for(size_t = 1; <= _rows ;i++){ for(size_t j = 1; j <= _cols l i++){ set_random(_matrix[(i-1)*_cols + (j-1)]); } }
with:
void set_random(int& val) { val = ... } void set_random(double& val) { val = ... } void set_random(char& val) { val = ... } // etc.
c++ templates matrix types
Comments
Post a Comment