Sunday, 15 April 2012

c++ - Template variable -



c++ - Template variable -

i can create template functions this:

template<typename t> t triviala(t in) { homecoming in; } template<typename t> t trivialb(t in) { homecoming in; } // calculation int main(int argc, char *argv[]) { triviala<int>(1); trivialb<int>(2); homecoming 0 }

however, do, (so user can specify precision want):

template<typename t> t triviala(t in){ homecoming in; } template<typename t> t trivialb(t in){ homecoming in; } // calculation int main(int argc, char *argv[]) { type thetype = int; //<<<<<<<<<<<<<<< right way this? triviala<thetype>(1); trivialb<thetype>(2); homecoming 0; }

so question is, how can hold datatype variable , pass template functions?

the old way see everwhere

typedef int thetype; typedef char*(*func_ptr)(int); //declare func_ptr pointer `char*(int)` function.

the newer more intuitive way:

using thetype = int; using func_ptr = char*(*)(int);

note makes new name type @ compile time, , cannot changed. ergo, useless runtime decisions. if need decide @ runtime, you'll need enumerate possible types , utilize enumeration, , possible type erasure via dynamic polymorphism.

simple way

template<class t> void do_stuff() { std::cout << 4; } enum use_type_enum {use_int, use_float}; int main() { use_type_enum use_type; std::cin >> use_type; switch(use_type) { case use_int: do_stuff<int>(); break; case use_float: do_stuff<float>(); break; default: throw std::runtime_error("incorrect math type"); } }

complex powerful way:

struct math_type { virtual ~math_type() {} virtual void print() const =0; }; template<class t> struct math_type_instance { t var; math_type_instance(t v) : var(v) {} virtual ~math_type_instance () {} virtual void print() const {std::cout << var;} }; enum use_type_enum {use_int, use_float}; int main() use_type_enum use_type; std::unique_ptr<math_type> variable; std::cin >> use_type; switch(use_type) { case use_int: variable = make_unique<math_type_instance<int>>(3); break; case use_float: variable = make_unique<math_type_instance<float>>(3); break; default: throw std::runtime_error("incorrect math type"); } variable->print(); }

c++ templates variables

No comments:

Post a Comment