我有一个std :: tuple类型,需要检查字符串是否可以反序列化为其中一个元素。元素和字符串的索引仅在运行时已知。
我的解决方案(如下所示)几乎可以正常工作,但在使用std::tuple_element
时会产生编译器错误,并给出:
错误:无效使用不完整类型'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;
try {
IsDeserializable<Tuple, std::tuple_size<Tuple>::value>::check(idx, in);
return true;
}
catch(...) {return false;}
}
// Example 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"));