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:
the rows should not fixed @ 3 anymore, number of rows should supported part of type.
i should able specify types should in each row. maybe want
double
first row ,int
second row. (making example 2 row class.)finally, should able attach other information
string
s rows. instance (continuing example in point 2), may want attachstring
first row customrss_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
Post a Comment