Parsing a C++ string into a tuple - c++

I am working on a simple CSV parser that would store the lines of a file in a tuple. This would be an easy task if it wasn't for the fact that the number of entries on the lines inside the file is a variable, as well as their type. Thus, the lines could be like that:
1,2.2,hello,18,world
The parser should be able to work like this:
ifstream file("input.csv");
SimpleCSVParser<int, float, string, int, string> parser(file);
Things get complex when I try to implement a function to parse the actual line. I still have not found a way to extract the next type from the parameter list to declare the variable before calling file >> var on it. I would also need to do this in a loop, somehow constructing a tuple from the results of each iteration.
So how do I parse the string into a tuple using plain C++11?
I tried this:
template <typename ...Targs>
tuple<Targs...> SimpleCSVParser<Targs...>::iterator::operator*() {
istringstream in(cur);
in.imbue(locale(locale(), new commasep)); // for comma separation
tuple<Targs...> t;
for (size_t i = 0; i < sizeof...(Targs); ++i) {
tuple_element<i,decltype(t)>::type first;
in >> first;
auto newt = make_tuple(first);
// what do I do here?
}
}
But it doesn't work since the tuple I use to extract types is empty.

It seems, you try to iterate over tuple indices/types which doesn't work, I think. What you can do, however, is to just call a read function for each member. The idea is to delegate processing of the tuple to a function which uses a parameter pack to expand an operation to an operation on each element. std::index_sequence<...> can be used to get the sequence of integers.
Something like this:
template <typename T>
bool read_tuple_element(std::istream& in, T& value) {
in >> value;
return true;
}
template <typename Tuple, std::size_t... I>
void read_tuple_elements(std::istream& in, Tuple& value, std::index_sequence<I...>) {
std::initializer_list<bool>{ read_tuple_element(in, std::get<I>(value))... });
}
template <typename ...Targs>
tuple<Targs...> SimpleCSVParser<Targs...>::iterator::operator*() {
std::istringstream in(cur);
in.imbue(std::locale(std::locale(), new commasep)); // for comma separation
std::tuple<Targs...> t;
read_tuple_elements(in, t, std::make_index_sequence<sizeof...(Targs)>{});
if (in) { // you may want to check if all data was consumed by adding && in.eof()
// now do something with the filled t;
}
else {
// the value could *not* successfully be read: somehow deal with that
}
}
The basic idea of the above code is simply to create a suitable sequence of calls to read_tuple_element(). Before jumping into the generic code, assume we'd want to implement reading of a std::tuple<T0, T1, T2> value with just three elements. We could implement the read using (using rte() instead of read_tuple_element() for brevity):
rte(get<0>(value)), rte(get<1>(value)), rte(get<2>(value));
Now, instead of writing this out for each number of elements, if we had an index sequence std::size_t... I we could get this sequence [nearly] using
rte(get<I>(value))...;
It isn't allowed to expand a parameter pack like this, though. Instead, the parameter pack needs to be put into some context. The code above uses a std::initializer_list<bool> for this purpose: the elements of a std::initializer_list<T> are constructed in the order listed. That is, we got
std::initializer_list<bool>{ rte(get<I>(value))... };
The missing bit is how to create the parameter pack I evaluating to a sequence of suitable indices. Conveniently, the standard library defines std::make_index_sequence<Size> which creates a std::index_sequence<I...> with a sequence of values for I as 0, 1, 2, ..., Size-1. So, calling read_tuple_elements() with std::make_index_sequence<sizeof...(Targs){} creates an object with a suitable list of arguments which can be deduced and then used to expand the tuple into a sequence of elements passed to read_tuple_element().

You cannot use tuples like this.
This would be an easy task if it wasn't for the fact that the number
of entries on the lines inside the file is a variable, as well as
their type.
If I understand, you only know your wanted tuples size and types at run-time while processing your file. Unfortunately this must be known at compile-time...
If you really want to use tuples, you have to make a pre treatment on your file to determine the data size and types. Then you can use the right tuples accordingly. But you cannot do that directly.

The usual method to do something like this via type erasure, for example using a union of all possible value types plus a flag indicating which is the actual entry
namespace generic_type {
struct generic
{
enum type { Void=0, Bool=1, Int=2, String=3, Float=4 };
type Type=Void;
union {
bool B;
std::int64_t I;
std::string S;
double X;
}
generic() = default;
generic(generic&&) = default;
generic(generic const&) = default;
generic(bool b) : Type(Bool), B(b) {}
generic(std::int64_t i) : Type(Int), I(i) {}
generic(std::uint64_t i) : Type(Int), I(i) {}
generic(std::string const&s) : Type(String), S(s) {}
generic(std::string &&s) : Type(String), S(std::move(s)) {}
generic(double x) : Type(Float), X(x) {}
};
namespace details {// auxiliary stuff
template<typename T, typename E=void>
struct traits
{
static constexpr generic::type Type=generic::Void;
static void get(generic const&) {}
};
template<>
struct traits<bool,void>
{
static constexpr generic::type Type=generic::Bool;
static bool get(generic const&x) { return x.B; }
};
template<typename T>
struct traits<T,enable_if_t<std::is_integral<T>::value>
{
static constexpr generic::type Type=generic::Int;
static T get(generic const&x) { return x.I; }
};
template<>
struct traits<std::string,void>
{
static constexpr generic::type Type=generic::Str;
static std::string const& get(generic const&x) { return x.S; }
static std::string&& get(generic&&x) { return std::move(x.S); }
};
template<T>
struct traits<float,enable_if<std::is_same<T,float>::value ||
std::is_same<T,double>::value>
{
static constexpr generic::type Type=generic::Float; };
static T get(generic const&x) { return x.X; }
}
}
template<typename T>
auto unsafe_extract(generic const&x)
-> decltype(details::traits<T>::get(x))
{ return details::traits<T>::get(x); }
template<typename T>
auto unsafe_extract(generic&&x)
-> decltype(details::traits<T>::get(std::move(x)))
{ return details::traits<T>::get(std::move(x)); }
template<typename T>
auto extract(generic const&x)
-> decltype(unsafe_extract(x))
{
if(details::traits<T>::Type != x.Type)
throw std::runtime_error("type mismatch in extract(generic)");
return unsafe_extract(x);
}
template<typename T>
auto extract(generic&&x)
-> decltype(unsafe_extract(std::move(x)))
{
if(details::traits<T>::Type != x.Type)
throw std::runtime_error("type mismatch in extract(generic&&)");
return unsafe_extract(std::move(x));
}
}
using generic_type::generic;
and then you can store your data in a std::vector<generic>.

for (size_t i = 0; i < sizeof...(Targs); ++i) {
tuple_element<i,decltype(t)>::type first;
in >> first;
auto newt = make_tuple(first);
// what do I do here?
}
This is runtime. You should consider using recursive functions using variadic templates. That would be compile time.

If you use std::tuple_cat you should be able to add each subsequent value to the tuple. I would also reccommend using C++14 return type deduction if I were you it eliminates the need to know the return type.

Related

Access std::vector<std::variant> value by index

I would like to access a member of std::vector<std::variant> by index. Considering the following snippet:
struct Data {
using data_types = std::variant<std::basic_string<char>, double, int>;
public:
template <class T>
void push_back(const T& t) {
m_data.push_back(t);
}
private:
std::vector<data_types> m_data;
};
int main()
{
Data d;
d.push_back(0);
d.push_back("string");
d.push_back(3.55);
}
I would like to access the values like d[0] (should return int) or d[1] (should return std::string).
What I have tried so far but what isn't working is to add the following public method to the existing struct:
template <class T>
T& operator[](const size_t &index) {
return std::visit([](const T& value) {
return static_cast<T>(value);
}, m_data[index]);
}
Any ideas how to achieve the desired result?
The type of an expression in C++ cannot depend on runtime parameters; basically it can only depend on types of the arguments, plus non-type template arguments.
So d[0] and d[1] must have the same type, as the type of the pieces of the expression are identical, and there are no non-type template arguments.
std::get<int>(d[0]) vs std::get<double>(d[1]) can differ in type.
std::get<1>(d[0]) vs std::get<2>(d[1]) can differ in type.
std::visit is a mechanism used to get around this; here, we create every a function object call, one for each possible type, and then pick one at runtime to actually call. However, the type returned from the visit still follows the above rule: it doesn't depend on what type is stored in the variant, and every possible type in the variant must have a valid instantiation of the function.
C++ type system is not a runtime type system. It is compile-time. Stuff like variant and dynamic_cast and any give some runtime exposure to it, but it is intentionally minimal.
If you are wanting to print the contents of a variant, you can do this:
std::visit([](auto& x){
std::cout << x;
}, d[0]);
the trick here is that each of the various types of variant have a lambda function body written for them (so they all must be valid). Then, at run time, the one actually in the variant is run.
You can also test the variant and ask if it has a specific type, either via std::get or manually.
bool has_int = std::visit([](auto& x){
return std::is_same_v<int, std::decay_t<decltype(x)>>::value;
}, d[0]);
this gives you a bool saying if d[0] has an int in it or not.
The next bit is getting insane. Please don't read this unless you fully understand how to use variants and want to know more:
You can even extract out the type index of the variant and pass that around as a run time value:
template<auto I>
using konstant_t = std::integral_constant<decltype(I),I>;
template<auto I>
constexpr konstant_t<I> konstant_v{};
template<auto...Is>
using venum_t = std::variant< konstant_t<Is>... >;
template<class Is>
struct make_venum_helper;
template<class Is>
using make_venum_helper_t = typename make_venum_helper<Is>::type;
template<std::size_t...Is>
struct make_venum_helper<std::index_sequence<Is...>>{
using type=venum_t<Is...>;
};
template<std::size_t N>
using make_venum_t = typename make_venum_helper<std::make_index_sequence<N>>::type;
template<std::size_t...Is>
constexpr auto venum_v( std::index_sequence<Is...>, std::size_t I ) {
using venum = make_venum_t<sizeof...(Is)>;
constexpr venum arr[]={
venum( konstant_v<Is> )...
};
return arr[I];
}
template<std::size_t N>
constexpr auto venum_v( std::size_t I ) {
return venum_v( std::make_index_sequence<N>{}, I );
}
template<class...Ts>
constexpr auto venum_v( std::variant<Ts...> const& v ) {
return venum_v< sizeof...(Ts) >( v.index() );
}
now you can do this:
using venum = make_venum_t<3>;
venum idx = venum_v(d[0]);
and idx holds the index of the engaged type in d[0]. This is only somewhat useful, as you still need std::visit to use it usefully:
std::visit([&](auto I) {
std::cout << std::get<I>( d[0] );
}, idx );
(within the lambda, I is a std::integral_constant, which can be constexpr converted to an integer.)
but lets you do some interesting things with it.
To extract a value from variant, use std::get:
struct Data
{
...
template <class T>
T& operator[](size_t index)
{
return std::get<T>(m_data[index]);
}
};
However, because this overloaded operator is a template, you can't use simple operator syntax to call it. Use the verbose syntax:
int main()
{
Data d;
d.push_back(0);
d.push_back("string");
d.push_back(3.55);
std::cout << d.operator[]<double>(2);
}
Or rename it to use a plain name instead of the fancy operator[].
Visitor pattern:
#include <iostream>
#include <string>
#include <variant>
#include <vector>
template <class ...Ts>
struct MultiVector : std::vector<std::variant<Ts...>> {
template <class Visitor>
void visit(std::size_t i, Visitor&& v) {
std::visit(v, (*this)[i]);
}
};
int main() {
MultiVector<std::string, int, double> vec;
vec.push_back(0);
vec.push_back("string");
vec.push_back(3.55);
vec.visit(2, [](auto& e) { std::cout << e << '\n'; });
}

Getting compile-time constant offsetof of base class in multiple-inheritance

Look at this example:
struct s77 {
char d[77];
};
struct s1 {
char d;
};
struct Foo: s77, s1 {
};
struct Off {
static const int v = std::size_t(static_cast<s1*>(static_cast<Foo*>(nullptr)+1)) - std::size_t(static_cast<Foo*>(nullptr)+1);
};
This code tries to put the offset of s1 in Foo into Off::v. This code compiles with GCC/clang (without any warnings), but fails to compile with VS2015/VS2017 (error C2131: expression did not evaluate to a constant)
Which compiler is correct?
Can I achieve this functionality in a standard conformant way? If it is not possible, is it possible to create a working solution which works with VS2015/VS2017? I'm willing to accept any working solution, even which has undefined behavior according to the standard (but happens to work with VS2015 and VS2017). Off::v must be a compile time constant.
My original problem is this: I have an own implementation of tuple, which is implemented with multiple inheritance (like clang's tuple). I'd like to create a compile-time constant "descriptor" for the tuple, which contains all of its members' offset in the tuple. This descriptor contains a function pointer for each tuple member too. If I'd create this descriptor by hand, it would look like this (for example):
struct Entry {
int offset;
void (*function)(void *member);
};
Entry descriptor[] = {
{ 0, &SomeType1::static_function },
{ 12, &SomeType2::static_function },
{ 20, &SomeType3::static_function }
};
The intention of this is that I could have a general function (which is not a template), which can use this descriptor to call a type-specific function on each tuple member:
void call(void *tuple, const Entry *entries, int n) {
for (int i=0; i<n; i++) {
entries[i].function(static_cast<char *>(tuple)+entries[i].offset);
}
}
(The reason of this solution instead of a templated call function is that call is actually a huge function in my real code, and entry[i].function calls cannot be factored out from it. I'd like to avoid massive code duplication.)
How about something like:
struct Entry {
void* (*data_member_getter)(void*);
void (*function)(void *member);
};
namespace details
{
template <std::size_t I, typename Tuple>
constexpr void* voidPGetter(void* tuple)
{
return &std::get<I>(*reinterpret_cast<Tuple*>(tuple));
}
template <typename Tuple, std::size_t I>
constexpr MakeEntry()
{
using type = std::tuple_element_t<I, Tuple>;
return { &voidPGetter<I, Tuple>, &type::static_function };
}
template <typename Tuple, std::size_t ... Is>
constexpr std::array<Entry, sizeof...(Is)>
ComputeEntryHelper(std::index_sequence<Is...>)
{
return {{MakeEntry<Is, Tuple>()...}};
}
}
template <typename Tuple>
constexpt auto ComputeEntry()
{
constexpr auto size = std::tuple_size<Tuple>::value;
return details::ComputeEntryHelper(std::make_index_sequence<size>());
}
And then
void call(void* tuple, const Entry* entries, int n) {
for (int i = 0; i != n; ++i) {
entries[i].function(entries[i].data_member_getter(tuple));
}
}
So instead of offset, having a function to get the data.

what is the standard way to do conversion based on the required type in a template function in c++

I am writing a class that hold several values as string and hold them in an array.
in one function, I need to offer the capability that the user request the value for one item in the list, but since we don't know the type of value, I need ask user how to convert it, so I am thinking of a template function.
sample code is here:
class myclass
{
vector<string> data;
myClass()
{
data=getData(); // data is filled, I don't know the data shape.
}
template <typename T>
T readData(int pos)
{
// here I should provide a way so if T is say int, then I convert data[pos] to int and then return back.
// I am thinking of using is_same<T, int> as follow:
if (std::is_same<T, int>::value)
{
return stio(data[pos]);
}
}
// is there any better way to do this?
}
Apparently this method require a lot of if statement and if the T is not in the list, I can not detect it during compile time.
So I am looking for a better way to do this.
Well one key here is that you'll need a return if your if-condition fails. But as far as a better way? Yeah, I'd say that an istringstream offers you the most power and dependability. With it you can write your function like:
template <typename T>
T readData(const size_t pos) {
T result{};
istringstream foo(data[pos]);
foo >> result;
return result;
}
Live Example
You can't do it that way because all the code in those ifs must be compilable.
You are looking for template specialization:
template<typename T>
T readData(int pos)
{
std::cerr << "type not supported" << std::cerr;
return T{};
}
template<int>
int readData(int pos)
{
return stio(data[pos]);
}
template<float>
float readData(int pos)
{
return something_that_returns_float(data[pos]);
}
You could use boost::lexical_cast<>, where the type that you want to get back is the template parameter.
In your example:
template< typename T> T readData( int pos)
{
return boost::lexical_cast< T>( data[ pos]);
}
Be aware that boost::lexical_cast<> throws if the conversion fails (i.e. 'hello world' -> int).
I would use std::function.
The user have possibility to use its own deserialize functions.
Something like the following should works;
class myclass
{
vector<string> data;
template <class T> //type STRING -> T
T readData(int pos, std::function<T(std::string&)> converter)
{
return converter(data[pos]);
}
};

Naming tuple elements

I am developping a some kind of tuple structure, and I would like to allow the user to use its elements as fields,
EXPLAINING :
this is my tuple :
template<typename ...Ts>
struct myTuple{
std::tuple<Ts...> data;
template<size_t I>
inline type<I>& get_t() { // type<I> is the I'th type
return std::get<I>(data);
}
// Other stuff
};
For the moment the user can have it this way :
struct UserStruct{
myTuple<int,bool,string> t;
// Other stuff
}
and use it like,
UserStruct ob;
ob.t.get_t<0>() = 0;
Which is a little bit complex... So i made it this way
struct UserStruct{
myTuple<int,bool,string> t;
decltype(mo.get_t<0>()) myInt() {
return mo.get_t<0>();
}
decltype(t.get_t<1>()) myChar() {
return t.get_t<1>();
}
decltype(t.get_t<2>()) myString() {
return t.get_t<2>();
}
};
so he can use it directly : myInt() = 0;
My goal is that he could use the tuple as if he had an int, bool, string data members without storing the references, which means I need a function ( or a functor ) to get the reference, so my solution is good, but it needs the user to define the functions. (And the getter looks much worse in the real code)
So I would like something like this :
struct UserStruct{
myTuple<int,bool,string> t;
MyFunctor<0> myInt; //or an alias to a function
MyFunctor<1> myChar;
MyFunctor<2> myString;
};
Code like MyFunctor<0> myInt; can't work without supplying t to the functor as well so it knows which tuple to link to. You could, however, add a macro to build the accessor for you that would assume the tuple name is t (or you supply it to the macro).
#define LINK_MEMBER(ID, NAME) decltype(t.get_t<ID>()) NAME() { \
return t.get_t<ID>(); \
}
Then your code would look like
struct UserStruct{
myTuple<int,bool,string> t;
LINK_MEMBER(0, myInt); //or an alias to a function
LINK_MEMBER(1, myChar);
LINK_MEMBER(2, myString);
};
Why write myInt() when you can write my<int>()? It's one more character, and allows you to just write:
template<typename ...Ts>
struct myTuple{
std::tuple<Ts...> data;
template <size_t I>
decltype(auto) my() { return std::get<I>(data); }
template <typename T>
decltype(auto) my() { return std::get<T>(data); }
};
using UserStruct = myTuple<int, bool, std::string>;
No need for alias functions, macros, etc, while also being nice and concise.

how to avoid undefined execution order for the constructors when using std::make_tuple

How can I use std::make_tuple if the execution order of the constructors is important?
For example I guess the execution order of the constructor of class A and the constructor of class B is undefined for:
std::tuple<A, B> t(std::make_tuple(A(std::cin), B(std::cin)));
I came to that conclusion after reading a comment to the question
Translating a std::tuple into a template parameter pack
that says that this
template<typename... args>
std::tuple<args...> parse(std::istream &stream) {
return std::make_tuple(args(stream)...);
}
implementation has an undefined execution order of the constructors.
Update, providing some context:
To give some more background to what I am trying to do, here is a sketch:
I want to read in some serialized objects from stdin with the help of CodeSynthesis XSD binary parsing/serializing. Here is an example of how such parsing and serialization is done: example/cxx/tree/binary/xdr/driver.cxx
xml_schema::istream<XDR> ixdr (xdr);
std::auto_ptr<catalog> copy (new catalog (ixdr));
I want to be able to specify a list of the classes that the serialized objects have (e.g. catalog, catalog, someOtherSerializableClass for 3 serialized objects) and store that information as a typedef
template <typename... Args>
struct variadic_typedef {};
typedef variadic_typedef<catalog, catalog, someOtherSerializableClass> myTypes;
as suggested in Is it possible to “store” a template parameter pack without expanding it?
and find a way to get a std::tuple to work with after the parsing has finished. A sketch:
auto serializedObjects(binaryParse<myTypes>(std::cin));
where serializedObjects would have the type
std::tuple<catalog, catalog, someOtherSerializableClass>
The trivial solution is not to use std::make_tuple(...) in the first place but to construct a std::tuple<...> directly: The order in which constructors for the members are called is well defined:
template <typename>
std::istream& dummy(std::istream& in) {
return in;
}
template <typename... T>
std::tuple<T...> parse(std::istream& in) {
return std::tuple<T...>(dummy<T>(in)...);
}
The function template dummy<T>() is only used to have something to expand on. The order is imposed by construction order of the elements in the std::tuple<T...>:
template <typename... T>
template <typename... U>
std::tuple<T...>::tuple(U...&& arg)
: members_(std::forward<U>(arg)...) { // NOTE: pseudo code - the real code is
} // somewhat more complex
Following the discussion below and Xeo's comment it seems that a better alternative is to use
template <typename... T>
std::tuple<T...> parse(std::istream& in) {
return std::tuple<T...>{ T(in)... };
}
The use of brace initialization works because the order of evaluation of the arguments in a brace initializer list is the order in which they appear. The semantics of T{...} are described in 12.6.1 [class.explicit.init] paragraph 2 stating that it follows the rules of list initialization semantics (note: this has nothing to do with std::initializer_list which only works with homogenous types). The ordering constraint is in 8.5.4 [dcl.init.list] paragraph 4.
As the comment says, you could just use initializer-list:
return std::tuple<args...>{args(stream)...};
which will work for std::tuple and suchlikes (which supports initializer-list).
But I got another solution which is more generic, and can be useful where initializer-list cannot be used. So lets solve this without using initializer-list:
template<typename... args>
std::tuple<args...> parse(std::istream &stream) {
return std::make_tuple(args(stream)...);
}
Before I explain my solution, I would like to discuss the problem first. In fact, thinking about the problem step by step would also help us to come up with a solution eventually. So, to simply the discussion (and thinking-process), lets assume that args expands to 3 distinct types viz. X, Y, Z, i.e args = {X, Y, Z} and then we can think along these lines, reaching towards the solution step-by-step:
First and foremost, the constructors of X, Y, and Z can be executed in any order, because the order in which function arguments are evaluated is unspecified by the C++ Standard.
But we want X to construct first, then Y, and Z. Or at least we want to simulate that behavior, which means X must be constructed with data that is in the beginning of the input stream (say that data is xData) and Y must be constructed with data that comes immediately after xData, and so on.
As we know, X is not guaranteed to be constructed first, so we need to pretend. Basically, we will read the data from the stream as if it is in the beginning of the stream, even if Z is constructed first, that seems impossible. It is impossible as long as we read from the input stream, but we read data from some indexable data structure such as std::vector, then it is possible.
So my solution does this: it will populate a std::vector first, and then all arguments will read data from this vector.
My solution assumes that each line in the stream contains all the data needed to construct an object of any type.
Code:
//PARSE FUNCTION
template<typename... args>
std::tuple<args...> parse(std::istream &stream)
{
const int N = sizeof...(args);
return tuple_maker<args...>().make(stream, typename genseq<N>::type() );
}
And tuple_maker is defined as:
//FRAMEWORK - HELPER ETC
template<int ...>
struct seq {};
template<int M, int ...N>
struct genseq : genseq<M-1,M-1, N...> {};
template<int ...N>
struct genseq<0,N...>
{
typedef seq<N...> type;
};
template<typename...args>
struct tuple_maker
{
template<int ...N>
std::tuple<args...> make(std::istream & stream, const seq<N...> &)
{
return std::make_tuple(args(read_arg<N>(stream))...);
}
std::vector<std::string> m_params;
std::vector<std::unique_ptr<std::stringstream>> m_streams;
template<int Index>
std::stringstream & read_arg(std::istream & stream)
{
if ( m_params.empty() )
{
std::string line;
while ( std::getline(stream, line) ) //read all at once!
{
m_params.push_back(line);
}
}
auto pstream = new std::stringstream(m_params.at(Index));
m_streams.push_back(std::unique_ptr<std::stringstream>(pstream));
return *pstream;
}
};
TEST CODE
///TEST CODE
template<int N>
struct A
{
std::string data;
A(std::istream & stream)
{
stream >> data;
}
friend std::ostream& operator << (std::ostream & out, A<N> const & a)
{
return out << "A" << N << "::data = " << a.data ;
}
};
//three distinct classes!
typedef A<1> A1;
typedef A<2> A2;
typedef A<3> A3;
int main()
{
std::stringstream ss("A1\nA2\nA3\n");
auto tuple = parse<A1,A2,A3>(ss);
std::cout << std::get<0>(tuple) << std::endl;
std::cout << std::get<1>(tuple) << std::endl;
std::cout << std::get<2>(tuple) << std::endl;
}
Output:
A1::data = A1
A2::data = A2
A3::data = A3
which is expected. See demo at ideone yourself. :-)
Note that this solution avoids the order-of-reading-from-the-stream problem by reading all the lines in the first call to read_arg itself, and all the later calls just read from the std::vector, using the index.
Now you can put some printf in the constructor of the classes, just to see that the order of construction is not same as the order of template arguments to the parse function template, which is interesting. Also, the technique used here can be useful for places where list-initialization cannot be used.
There's nothing special about make_tuple here. Any function call in C++ allows its arguments to be called in an unspecified order (allowing the compiler freedom to optimize).
I really don't suggest having constructors that have side-effects such that the order is important (this will be a maintenance nightmare), but if you absolutely need this, you can always construct the objects explicitly to set the order you want:
A a(std::cin);
std::tuple<A, B> t(std::make_tuple(a, B(std::cin)));
This answer comes from a comment I made to the template pack question
Since make_tuple deduces the tuple type from the constructed components and function arguments have undefined evaluation ordder, the construction has to happen inside the machinery, which is what I proposed in the comment. In that case, there's no need to use make_tuple; you could construct the tuple directly from the tuple type. But that doesn't order construction either; what I do here is construct each component of the tuple, and then build a tuple of references to the components. The tuple of references can be easily converted to a tuple of the desired type, provided the components are easy to move or copy.
Here's the solution (from the lws link in the comment) slightly modified, and explained a bit. This version only handles tuples whose types are all different, but it's easier to understand; there's another version below which does it correctly. As with the original, the tuple components are all given the same constructor argument, but changing that simply requires adding a ... to the lines indicated with // Note: ...
#include <tuple>
#include <type_traits>
template<typename...T> struct ConstructTuple {
// For convenience, the resulting tuple type
using type = std::tuple<T...>;
// And the tuple of references type
using ref_type = std::tuple<T&...>;
// Wrap each component in a struct which will be used to construct the component
// and hold its value.
template<typename U> struct Wrapper {
U value;
template<typename Arg>
Wrapper(Arg&& arg)
: value(std::forward<Arg>(arg)) {
}
};
// The implementation class derives from all of the Wrappers.
// C++ guarantees that base classes are constructed in order, and
// Wrappers are listed in the specified order because parameter packs don't
// reorder.
struct Impl : Wrapper<T>... {
template<typename Arg> Impl(Arg&& arg) // Note ...Arg, ...arg
: Wrapper<T>(std::forward<Arg>(arg))... {}
};
template<typename Arg> ConstructTuple(Arg&& arg) // Note ...Arg, ...arg
: impl(std::forward<Arg>(arg)), // Note ...
value((static_cast<Wrapper<T>&>(impl)).value...) {
}
operator type() const { return value; }
ref_type operator()() const { return value; }
Impl impl;
ref_type value;
};
// Finally, a convenience alias in case we want to give `ConstructTuple`
// a tuple type instead of a list of types:
template<typename Tuple> struct ConstructFromTupleHelper;
template<typename...T> struct ConstructFromTupleHelper<std::tuple<T...>> {
using type = ConstructTuple<T...>;
};
template<typename Tuple>
using ConstructFromTuple = typename ConstructFromTupleHelper<Tuple>::type;
Let's take it for a spin
#include <iostream>
// Three classes with constructors
struct Hello { char n; Hello(decltype(n) n) : n(n) { std::cout << "Hello, "; }; };
struct World { double n; World(decltype(n) n) : n(n) { std::cout << "world"; }; };
struct Bang { int n; Bang(decltype(n) n) : n(n) { std::cout << "!\n"; }; };
std::ostream& operator<<(std::ostream& out, const Hello& g) { return out << g.n; }
std::ostream& operator<<(std::ostream& out, const World& g) { return out << g.n; }
std::ostream& operator<<(std::ostream& out, const Bang& g) { return out << g.n; }
using std::get;
using Greeting = std::tuple<Hello, World, Bang>;
std::ostream& operator<<(std::ostream& out, const Greeting &n) {
return out << get<0>(n) << ' ' << get<1>(n) << ' ' << get<2>(n);
}
int main() {
// Constructors run in order
Greeting greet = ConstructFromTuple<Greeting>(33.14159);
// Now show the result
std::cout << greet << std::endl;
return 0;
}
See it in action on liveworkspace. Verify that it constructs in the same order in both clang and gcc (libc++'s tuple implementation holds tuple components in the reverse order to stdlibc++, so it's a reasonable test, I guess.)
To make this work with tuples which might have more than one of the same component, it's necessary to modify Wrapper to be a unique struct for each component. The easiest way to do this is to add a second template parameter, which is a sequential index (both libc++ and libstdc++ do this in their tuple implementations; it's a standard technique). It would be handy to have the "indices" implementation kicking around to do this, but for exposition purposes, I've just done a quick-and-dirty recursion:
#include <tuple>
#include <type_traits>
template<typename T, int I> struct Item {
using type = T;
static const int value = I;
};
template<typename...TI> struct ConstructTupleI;
template<typename...T, int...I> struct ConstructTupleI<Item<T, I>...> {
using type = std::tuple<T...>;
using ref_type = std::tuple<T&...>;
// I is just to distinguish different wrappers from each other
template<typename U, int J> struct Wrapper {
U value;
template<typename Arg>
Wrapper(Arg&& arg)
: value(std::forward<Arg>(arg)) {
}
};
struct Impl : Wrapper<T, I>... {
template<typename Arg> Impl(Arg&& arg)
: Wrapper<T, I>(std::forward<Arg>(arg))... {}
};
template<typename Arg> ConstructTupleI(Arg&& arg)
: impl(std::forward<Arg>(arg)),
value((static_cast<Wrapper<T, I>&>(impl)).value...) {
}
operator type() const { return value; }
ref_type operator()() const { return value; }
Impl impl;
ref_type value;
};
template<typename...T> struct List{};
template<typename L, typename...T> struct WrapNum;
template<typename...TI> struct WrapNum<List<TI...>> {
using type = ConstructTupleI<TI...>;
};
template<typename...TI, typename T, typename...Rest>
struct WrapNum<List<TI...>, T, Rest...>
: WrapNum<List<TI..., Item<T, sizeof...(TI)>>, Rest...> {
};
// Use WrapNum to make ConstructTupleI from ConstructTuple
template<typename...T> using ConstructTuple = typename WrapNum<List<>, T...>::type;
// Finally, a convenience alias in case we want to give `ConstructTuple`
// a tuple type instead of a list of types:
template<typename Tuple> struct ConstructFromTupleHelper;
template<typename...T> struct ConstructFromTupleHelper<std::tuple<T...>> {
using type = ConstructTuple<T...>;
};
template<typename Tuple>
using ConstructFromTuple = typename ConstructFromTupleHelper<Tuple>::type;
With test here.
I believe the only way to manually unroll the definition. Something like the following might work. I welcome attempts to make it nicer though.
#include <iostream>
#include <tuple>
struct A { A(std::istream& is) {}};
struct B { B(std::istream& is) {}};
template <typename... Ts>
class Parser
{ };
template <typename T>
class Parser<T>
{
public:
static std::tuple<T> parse(std::istream& is) {return std::make_tuple(T(is)); }
};
template <typename T, typename... Ts>
class Parser<T, Ts...>
{
public:
static std::tuple<T,Ts...> parse(std::istream& is)
{
A t(is);
return std::tuple_cat(std::tuple<T>(std::move(t)),
Parser<Ts...>::parse(is));
}
};
int main()
{
Parser<A,B>::parse(std::cin);
return 1;
}