Sunday, 15 February 2015

c++ - Check a string is convertable to the n-th element of a std::tuple -



c++ - Check a string is convertable to the n-th element of a std::tuple -

i have std::tuple type , need check if string can de-serialized 1 of elements. index of element , string known @ run time.

my solution (below) works creates compiler errors when using std::tuple_element, giving:

error: invalid utilize of incomplete type ‘struct std::tuple_element<0ul, std::tuple&>

#include <sstream> #include <tuple> template<class tuple, std::size_t n> struct isdeserializable { static void check(std::size_t idx, std::stringstream& in) { isdeserializable<tuple, n-1>::check(idx, in); if (idx == n-1) { typename std::tuple_element<n-1,tuple>::type tmp; in >> tmp; } } }; template<class tuple> struct isdeserializable<tuple, 1> { static void check(std::size_t idx, std::stringstream& in) { if (idx == 0) { typename std::tuple_element<0,tuple>::type tmp; in >> tmp; } } }; template<class tuple> bool is_deserializable(std::size_t idx, const std::string& val) { std::stringstream in; in << val; seek { isdeserializable<tuple, std::tuple_size<tuple>::value>::check(idx, in); homecoming true; } catch(...) {return false;} } // illustration usage std::tuple<int,double,char> mytuple; assert(is_deserializable<mytuple>(0,"4")); assert(is_deserializable<mytuple>(1,"56.5")); assert(is_deserializable<mytuple>(2,"h")); assert(!is_deserializable<mytuple>(0,"4.3")); assert(!is_deserializable<mytuple>(1,"hello")); assert(!is_deserializable<mytuple>(2,"42"));

c++ templates c++11 tuples

No comments:

Post a Comment