1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75
|
#include <iostream>
#include <string>
#include <tuple>
#include <vector>
// ORIGINAL
template < typename... T > using table_type = std::vector< std::tuple<T...> > ;
template < typename... T, typename... ARGS > void add_row( table_type<T...>& table, ARGS&&... args )
{ table.push_back( std::tuple<T...>( std::forward<ARGS>(args)... ) ) ; }
template < typename T, typename... U > T get( table_type<U...>& table, std::size_t pos )
{ return std::get<T>( table[pos] ) ; }
template < typename T, typename... U > const T& get( const table_type<U...>& table, std::size_t pos )
{ return std::get<T>( table[pos] ) ; }
template < std::size_t N, typename... U >
typename std::tuple_element< N, std::tuple<U...> >::type& get( table_type<U...>& table, std::size_t pos )
{ return std::get<N>(table[pos]) ; }
template < std::size_t N, typename... U >
const typename std::tuple_element< N, std::tuple<U...> >::type& get( const table_type<U...>& table, std::size_t pos )
{ return std::get<N>(table[pos]) ; }
//CLASS
template <typename... T>
class Table {
public:
Table() = default;
template < std::size_t Column >
typename std::tuple_element < Column, std::tuple<T...> >::type& get(std::size_t row)
{
return std::get<Column> (m_Table[row]);
}
void addRow( T&&... args )
{
m_Table.push_back( std::tuple<T...>(std::forward<T>(args)...) ) ;
}
private:
std::vector<std::tuple<T...>> m_Table;
};
int main()
{
//ORIGINAL
table_type< std::string, double, bool > table ;
add_row( table, "Hello", 2.3, true ) ;
add_row( table, "world", -21.4, false ) ;
std::cout << get<std::string>( table, 0 ) << '\n' // hello
<< get<0>( table, 1 ) << '\n' // world
<< get<double>( table, 1 ) << '\n' // -21.4
<< std::boolalpha << get<2>( table, 0 ) // true
<< "\n--------------\n" ;
for( const auto& tup : table ) {
std::cout << std::get<std::string>(tup) << ' ' << std::get<double>(tup) << ' ' << std::get<bool>(tup) << '\n' ;
}
//CLASS
std::cout<< "----------------\n";
Table< std::string, double, bool > table2;
table2.addRow( "Hello", 2.3, true );
table2.addRow( "world", -21.4, false);
std::cout << table2.get<0>(0) << '\n' // hello
<< table2.get<0>(1) << '\n' // world
<< table2.get<1>(1) << '\n' //-21.4
<< std::boolalpha << table2.get<2>(0) << '\n' //true
<< "\n-------------\n" ;
return 0;
}
|