Can this be accomplished with templates in C++? -


this simple class represents 3 rows of doubles, string information attached each row:

struct threerows {   std::vector<double> row1;   std::vector<double> row2;   std::vector<double> row3;    std::string row1info;   std::string row2info;   std::string row3info; }; 

what want generalize type in following ways:

  1. the rows should not fixed @ 3 anymore, number of rows should supported part of type.

  2. i should able specify types should in each row. maybe want double first row , int second row. (making example 2 row class.)

  3. finally, should able attach other information strings rows. instance (continuing example in point 2), may want attach string first row custom rss_feed second row.

if templates allowed (which don't), want type out obtain type:

rows<{double,int}, {string,rss_feed}> 

the number of rows being determined that, or if had to:

rows<{double,int}, {string,rss_feed}, 2> 

but not possible.

can done, , if so, how work class template? how @ vectors , info objects , work them?

this can done using std::tuple specify list of types. need declare primary template take 2 parameters, create partial specialization type parameters tuples. in partial specialization, can use argument deduction capture template parameters of tuple , re-use them our purposes. create new template purposes of specifying list of types (i.e. types<int,double>), tuple nice in case because need have way access the individual rows anyway, , std::tuple provides built-in way through std::get<i>. using tuple template parameters may make more obvious use std::get access rows.

here's complete example:

#include <string> #include <tuple> #include <vector>  // primary template template <typename rowtuple,typename rowinfotuple> struct rows;  // variadic partial specialization  template <typename... rowtypes,typename... rowinfotypes> struct rows<std::tuple<rowtypes...>,std::tuple<rowinfotypes...>> {   // use variadic expansion make tuple of vectors   std::tuple<std::vector<rowtypes>...> rows;   std::tuple<rowinfotypes...> rowinfos; };  struct rss_feed { };  int main(int,char**) {   rows<     std::tuple<double,int>,     std::tuple<std::string,rss_feed>   > data;    std::get<0>(data.rows).push_back(1.5);   std::get<1>(data.rows).push_back(2);   std::get<0>(data.rowinfos) = "info";   std::get<1>(data.rowinfos) = rss_feed();   return 0; } 

Comments

Popular posts from this blog

linux - Does gcc have any options to add version info in ELF binary file? -

android - send complex objects as post php java -

charts - What graph/dashboard product is facebook using in Dashboard: PUE & WUE -