Info
-
Did you know that Circle Meta-model allows to convert string to a type?
Example
int main() {
@meta std::string type = "int";
@type_id(type) i = 42; // string -> type
return i; // returns int = 4
}
Puzzle
- Can you implement
strings_to_tuple
function which converts given strings into astd::tuple
of them?
template<class... Ts>
constexpr auto strings_to_tuple(Ts...); // TODO
struct foo {
int id{};
};
int main() {
using namespace boost::ut;
"string types to tuple"_test = [] {
"empty"_test = [] {
auto ts = strings_to_tuple();
expect(std::is_same_v<std::tuple<>, decltype(ts)>);
};
"simple types"_test = [] {
auto ts = strings_to_tuple([]{return "int";}, []{return "double";});
std::get<0>(ts) = 4;
std::get<1>(ts) = 2.;
expect(4_i == std::get<0>(ts) and 2._d == std::get<1>(ts));
};
"mix types"_test = [] {
auto ts = strings_to_tuple([]{return "unsigned";}, []{return "foo";},[]{return "int";});
std::get<0>(ts) = 1.;
std::get<1>(ts).id = 2;
std::get<2>(ts) = 3;
expect(1_u == std::get<0>(ts) and 2_i == std::get<1>(ts).id and 3_i == std::get<2>(ts));
};
};
}
Solutions
template<class... Ts>
constexpr auto strings_to_tuple(Ts...) {
return std::tuple<(@type_id(Ts{}()))...>{};
}
template<class... Ts>
constexpr auto strings_to_tuple(Ts...args )
{
auto toTypedObj = []( auto arg ){
constexpr const char * tName = arg();
return @type_id(tName){};
};
return std::make_tuple(toTypedObj(args)...);
}
constexpr auto strings_to_tuple(Ts...) {
return std::tuple<@type_id(Ts{}())...>{};
}
template<class... Ts>
constexpr auto strings_to_tuple(Ts ...) {
return std::make_tuple(@type_id(Ts{}()){}...);
}