Skip to content

Latest commit

 

History

History
101 lines (78 loc) · 2.31 KB

239.md

File metadata and controls

101 lines (78 loc) · 2.31 KB
Info

Example

int main() {
  @meta std::string type = "int";
  @type_id(type) i = 42; // string -> type
  return i;              // returns int = 4
}

https://godbolt.org/z/138zW9PvT

Puzzle

  • Can you implement strings_to_tuple function which converts given strings into a std::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));
    };
  };
}

https://godbolt.org/z/PsEjEKfvd

Solutions

template<class... Ts>
constexpr auto strings_to_tuple(Ts...) {
    return std::tuple<(@type_id(Ts{}()))...>{};
}

https://cpp-tip-of-the-week.godbolt.org/z/xzjP1fWbx

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)...);
}

https://godbolt.org/z/hhcT76vTh

constexpr auto strings_to_tuple(Ts...) {
  return std::tuple<@type_id(Ts{}())...>{};
}

https://godbolt.org/z/rej46v8a9

template<class... Ts>
constexpr auto strings_to_tuple(Ts ...) {
    return std::make_tuple(@type_id(Ts{}()){}...);
}

https://godbolt.org/z/4M3M7c5Mz