我是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
您不可能让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;
只要type
是constexpr
并且具有constexpr运算符[]
。