i have kind of code :
template <typename t1, typename t2 = void, typename t3 = void, typename t4 = void, typename t5 = void> std::set<std::type_info const*> myclass<t1,t2,t3,t4,t5>::get_types() { std::set<std::type_info const*> t; t.push_back(&typeid(t1)); if(typeid(t2) != typeid(void)) t.push_back(&typeid(t2)); else return; if(typeid(t3) != typeid(void)) t.push_back(&typeid(t3)); else return; if(typeid(t4) != typeid(void)) t.push_back(&typeid(t4)); else return; if(typeid(t5) != typeid(void)) t.push_back(&typeid(t5)); else return; }
is there way make loop on templates types t2
t5
avoid redundant code ?
note: don't use c++11. use boost.
yes can boost mpl using facilities of boost::mpl::vector
, boost::mpl::for_each
example below:
code:
#include <iostream> #include <typeinfo> #include <vector> #include <boost/mpl/vector.hpp> #include <boost/mpl/for_each.hpp> #include <boost/mpl/placeholders.hpp> template <typename t> struct wrap {}; class bar { std::vector<std::type_info const*> &types; public: bar(std::vector<std::type_info const*> &types_) : types(types_) {} template<typename t> void operator()(wrap<t>) const { if(typeid(t) != typeid(void)) types.push_back(&typeid(t)); } }; template<typename t1, typename t2 = void, typename t3 = void, typename t4 = void, typename t5 = void> struct foo { std::vector<std::type_info const*> get_types() const { std::vector<std::type_info const*> out; boost::mpl::for_each<boost::mpl::vector<t1, t2, t3, t4, t5>, wrap<boost::mpl::placeholders::_1> >(bar(out)); return out; } }; int main() { foo<int, long, double> foo; std::vector<std::type_info const*> types = foo.get_types(); for(int i(0), isz(types.size()); < isz; ++i) { std::cout << types[i]->name() << std::endl; } }
Comments
Post a Comment