for example, have template function used iterate vector in vector:
template<class t> void test(t t){ for(auto tt : t){ test(tt); } } which has pair special case, pair type may double,float,int,string,...:
pair<double,double> pair<double,float> pair<double,int> pair<double,string> pair<float,double> pair<float,float> pair<float,int> pair<float,string> pair<int,double> pair<int,float> pair<int,int> pair<int,string> pair<string,double> pair<string,float> pair<string,int> pair<string,string> the template may work pair.first independent of pair.second (may add element json,write file,... use printf represent):
template<> void test(pair<double,double> p){ printf("%f,",p.first); printf("%f\n",p.second); } template<> void test(pair<double,float> p){ printf("%f,",p.first); printf("%f\n",p.second); } . . . the code works,but number of template function horrible because needs 16 templates, possible separate , group template special case first , second needs 8 templates this:
pair<double,t> pair<float,t> pair<int,t> pair<string,t> pair<t,double> pair<t,float> pair<t,int> pair<t,string> i try following cannot compile:
template<class second> void test(pair<double,second> p){ printf("%f,",p.first); test<double,second>(p); } template<class second> void test(pair<float,second> p){ printf("%f,",p.first); test<double,second>(p); } . . . template<class first> void test(pair<first,int> p){ printf("%d\n",p.second); } template<class first> void test(pair<first,string> p){ printf("%s\n",p.second.c_str()); } is possible rewrite template this?
namespace details { template<class t> using is_wanted_type = std::integral_constant<bool, std::is_same<int, t>{} || std::is_same<float, t>{} || std::is_same<double, t>{} || std::is_same<std::string, t>{}>; void process_first(int) { /* ... */ } void process_first(float) { /* ... */ } void process_first(double) { /* ... */ } void process_first(const std::string &) { /* ... */ } void process_second(int) { /* ... */ } void process_second(float) { /* ... */ } void process_second(double) { /* ... */ } void process_second(const std::string &) { /* ... */ } } template<class t1, class t2> std::enable_if_t<details::is_wanted_type<t1>{} && details::is_wanted_type<t2>{}> test(const std::pair<t1, t2> &p) { details::process_first(p.first); details::process_second(p.second); }
Comments
Post a Comment