c++ - How to use RTTI to determine the behavior of code -


i have piece of code use rtti case selector

#include <iostream> #include <vector> #include <typeinfo> #include <complex> #include <algorithm>  using namespace std;  typedef complex<int> data; typedef std::vector< data > list;  template <typename t> void zeros(t &v) {   if (typeid(typename t::value_type)==typeid(complex<int>))     std::fill(v.begin(), v.end(), complex<int>(0, 0));   else std::fill(v.begin(), v.end(), static_cast<typename t::value_type>(0)); }  int main(int argc, char *argv[]) {   list a;    zeros(a);   return 0; } 

in above code, use typename t::value_type determine data type of list, if there complex fill list complex zero. otherwise, make 0 of corresponding type. in above code, if set data int, compile , run without problem. if set other type, fail compile. wonder if there way make above code work different type of data (for float, double, long, int, complex, complex , complex).

p.s. reason want fill vector in 2 cases because going create own complex reason , have tell code how create complex 0 or real zero. testing, can't make work built-in datatype

it seems want both default initialized complex (0, 0), , 0 initialized int. can achieve using value initialization:

template <typename t> void zeros(t &v) {     std::fill(v.begin(), v.end(), typename t::value_type{}); } 

if want perform branching depending on t::value_type, better use type trait, following one:

template<typename t> struct default_value {     static const t value; };  template<> struct default_value<std::complex<int>> { // assuming you'll use other complex type     static const std::complex<int> value; };  template<typename t> const t default_value<t>::value = t{}; const std::complex<int> default_value<std::complex<int>>::value = std::complex<int>(0, 0);  // use template <typename t> void zeros(t &v) {     std::fill(v.begin(), v.end(), default_value<typename t::value_type>::value); } 

but again, default construction , value initialization built in types should enough.


Comments

Popular posts from this blog

java - Run a .jar on Heroku -

java - Jtable duplicate Rows -

validation - How to pass paramaters like unix into windows batch file -