【问题标题】:How to convert a string representation of a type to the type itself in C++?如何将类型的字符串表示形式转换为 C++ 中的类型本身?
【发布时间】:2021-03-24 14:53:10
【问题描述】:

我是 C++ 新手,需要将类型的字符串表示形式转换为类型本身,如下所示:

"int"int
"float"float
等等……

但是,实现它似乎非常困难。例如,在伪代码中:

//how to implement this function or something like this...
auto gettype(string typestr);

//usage
string types[4] = {"int", "double", "float", "string", ...};
gettype(type[0]) val; //then the type of val is int

【问题讨论】:

  • 如果你假设要让它工作,你打算如何初始化val“需要将类型的字符串表示形式转换为类型本身”——我觉得这不太可能。 actual problem 是什么?
  • 为什么需要这个?您要解决什么实际问题?
  • 一个函数只能有一个返回类型。仅仅因为它被声明为auto 并不意味着它可以根据输入而改变。我想你有一个xy-problem
  • @Patrick Roberts 假设它的值也是从字符串转换而来的
  • 你想写解释器吗? ChaiScript 之类的东西?

标签: c++ decltype


【解决方案1】:

没有办法让gettype(type[0]) val; 成为声明。

我能想到的最接近的应该是

constexpr char int_t[] = "int";
constexpr char double_t[] = "double";
constexpr char float_t[] = "float";
constexpr char string_t[] = "string";

constexpr const char * types[] = { int_t, double_t, float_t, string_t };

template <const char *> struct gettype;

template<> struct gettype<int_t> { using type = int; };
template<> struct gettype<double_t> { using type = double; };
template<> struct gettype<float_t> { using type = float; };
template<> struct gettype<string_t> { using type = std::string; };

template <const char * name> using gettype_t = typename gettype<name>::type;

这要求参数是编译时间常数,但你可以有

gettype_t<type[0]> val;

只要typeconstexpr 并且有constexpr operator[]

【讨论】:

  • std::variant&lt;tag&lt;int&gt;, tag&lt;double&gt;, tag&lt;float&gt;, tag&lt;std::string&gt;&gt; 可能是一个运行时解决方案。
  • @Jarod42 这对声明 val 有何帮助?
  • 然后你可以std::visit 并调用从标签创建类型并完成工作的模板方法。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-02-01
  • 2020-11-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多