提问者:小点点

如何在C++中将一个类型的字符串表示形式转换为该类型本身?


我是C++的新手,需要将一个类型的字符串表示形式转换为该类型本身,比如:“int”转换为int,“float”转换为float,……但似乎很难实现。

例如在seudo代码中:

//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


共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运算符[]

相关问题


MySQL Query : SELECT * FROM v9_ask_question WHERE 1=1 AND question regexp '(何在|c++|中将|类型|字符串|形式|转|换为|类型)' ORDER BY qid DESC LIMIT 20
MySQL Error : Got error 'repetition-operator operand invalid' from regexp
MySQL Errno : 1139
Message : Got error 'repetition-operator operand invalid' from regexp
Need Help?