c++ - Why does this multiply template code cause overflow? -



c++ - Why does this multiply template code cause overflow? -

i have template here multiplies numbers this:

if pass in 2 , 5 template arguments, generate 5 numbers multiplied starting 2.

multiply_n_times<2, 5> should equal pack<2, 4, 16, 256>

this tried

class="lang-c++ prettyprint-override">template<int value, int count, int... is> struct multiply_n_times : multiply_n_times<value*value, count-1, is..., value> { }; template<int value, int... is> struct multiply_n_times<value, 0, is...> : pack<is...> { };

and when instantiate error:

class="lang-c++ prettyprint-override">main.cpp: in instantiation of 'struct multiply_n_times<65536, 1, 2, 4, 16, 256>': main.cpp:15:8: recursively required 'struct multiply_n_times<4, 4, 2>' main.cpp:15:8: required 'struct multiply_n_times<2, 5>' main.cpp:39:17: required here` main.cpp:15:8: error: overflow in constant look [-fpermissive] struct multiply_n_times : multiply_n_times<value*value, count-1, is..., value> { };

what did wrong here?

the lastly recursion first argument gets discarded has overflow.

so skip it:

template<int value, int... is> struct multiply_n_times<value, 1, is...> : pack<is..., value> { };

now never calculate value*value won't use.

leave 0 specialization if need 0 length list of squares.

c++

Comments

Popular posts from this blog

model view controller - MVC Rails Planning -

ruby on rails - Devise Logout Error in RoR -

html - Submenu setup with jquery and effect 'fold' -