这是我想出的
#include <iostream>
#include <algorithm>
#include <iterator>
#include <tuple>
#include <typeinfo>
using std::tuple;
using std::get;
template< class... Args >
struct parser;
// Specialization for std::tuple
template< class... Args >
struct parser<tuple<Args...>> {
typedef tuple<Args...> tuple_type;
static tuple_type parse( std::istream& is ) {
tuple<Args...> result;
_parse<0, tuple_type>::parse(is, result);
return result;
}
private:
template< size_t N, class T >
struct _parse;
template< size_t N, class A0, class... An >
struct _parse<N, tuple<A0, An...>> {
static void parse( std::istream& is, tuple_type& t ) {
std::cout << "Enter " << typeid(A0).name() << ": ";
if (!( is >> get<N>(t) ))
{ std::cout << "Bad input!\n"; is.clear(); }
is.get();
// Recurse on the rest of the list
_parse<N+1, tuple<An...>>::parse(is, t);
}
};
// Termination
template< size_t N >
struct _parse<N, tuple<>> {
static void parse( std::istream& is, tuple_type& t ) {
/* */
}
};
};
int main() {
typedef tuple<int, double, char> tuple_type;
tuple_type t = parser<tuple_type>::parse( std::cin );
std::cout << get<0>(t) << ", " << get<1>(t) << ", " << get<2>(t) << std::endl;
}
输出
$ ./a.out
Enter i: 0
Enter d: 0.0
Enter c: w
0, 0, w
$ ./a.out
Enter i: 0
Enter d: 0.0
Enter c: w
0, 0, w