c++ - 获取与字符串对应的类型,如 int、float 等

标签 c++ c++11 templates

在 C++ 中是否有任何方法(函数/结构/模板)等,如果我们提供 int、float 等字符串作为输入,然后它返回相应的类型。为了详细说明一个场景,假设从 DB 我能够检索列的数据类型说 ITEM_NAME 具有 varchar 类型(如 std::string)所以现在我想声明一个 c++ 变量 item_name(std::string) 其类型将是对应的到此列 ITEM_NAME(varchar)。以下是我尝试过的东西(示例代码),但这不起作用:

template<string coltype>
struct DatabaseType
{
   typedef COL_TYPE std::string;
};

template<string coltype="int">
{
   typedef COL_TYPE int;
};

std::string getDBType()
{
return "int"; 
}
int main()
{
DataBaseType<std::string("int")>::COL_TYPE x;
//need to call another overloaded function that returns value corresponding to DB Column name in x
getDBValue("ITEM_NAME",x); //note this is already defined overloaded function that can take std::string,float and int in place of second argument
return 0;
};

最佳答案

这很可能是无稽之谈,但原则上是可以实现的:

template<size_t N>
struct DatabaseType
{
   typedef int COL_TYPE;
};

unsigned constexpr const_hash(char const *input) {
   return *input ?
      static_cast<unsigned int>(*input) + 33 * const_hash(input + 1) :
      5381;
}

template<>
struct DatabaseType<const_hash("int")>
{
   typedef int COL_TYPE;
};

template<>
struct DatabaseType<const_hash("float")>
{
   typedef float COL_TYPE;
};

template<>
struct DatabaseType<const_hash("string")>
{
   typedef std::string COL_TYPE;
};

void main()
{
   auto i = DatabaseType<const_hash("int")>::COL_TYPE(10);
   auto f = DatabaseType<const_hash("float")>::COL_TYPE(1.0);
   auto f = DatabaseType<const_hash("string")>::COL_TYPE("dasdas");
}

这没有意义,因为使用枚举更容易:

enum Types
{
   TYPE_INT,
   TYPE_FLOAT,
   TYPE_STRING
};

template<Types N>
struct DatabaseType
{
   typedef int COL_TYPE;
};

template<>
struct DatabaseType<TYPE_INT>
{
   typedef int COL_TYPE;
};

template<>
struct DatabaseType<TYPE_FLOAT>
{
   typedef float COL_TYPE;
};

template<>
struct DatabaseType<TYPE_STRING>
{
   typedef std::string COL_TYPE;
};



void main()
{
   auto i = DatabaseType<TYPE_INT>::COL_TYPE(10);
   auto f = DatabaseType<TYPE_FLOAT>::COL_TYPE(1.0f);
   auto f = DatabaseType<TYPE_STRING>::COL_TYPE("dasdas");
}

关于c++ - 获取与字符串对应的类型,如 int、float 等,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53650136/

相关文章:

c++ - 我可以将 std::map 的内容 move 分配到另一个 std::map 吗?

c++ - 可以组合部分模板特化来生成隐式生成的共享代码路径吗?

c++ - 数组中最大的 double

c++ - 如何搜索 PDF?

c++ - 带有 C++ 模板的 SWIG : undefined symbol

c++ - Boost 库中的编译失败(program_options)

c++ - 成员模板静态函数的类型特征

C++酒店入住与跳过13楼迭代编码项目(非IT系学生)

c++ - 如何为类型列表中的每个继承类型调用非默认构造函数?

templates - 自定义 Prestashop 管理模块