c++ - 获取与 int、float 等字符串对应的类型
问题描述
在 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");
}
推荐阅读
- django - 在 Django 中,尝试使用 base64 编码对 .wav 文件进行编码,但出现此错误
- javascript - 如何知道 JavaScript 中哪个函数调用了另一个函数?
- clojure - 带有基座 clojure 服务器的通用 [/*proxy :any] 和特定 [/service/x :post..] 路由
- html - 将 css 属性分配给父级,而不是子级
- javascript - JavaScript - 在同一窗口/选项卡中打开链接
- sql-server - 使用 sql server 将数字从 002541500(后 4 位为小数位)转换为 254.1500
- xml - 简单转换反序列化:匹配元素错误
- speech-recognition - 如何在 dictation.io/speech 中捕捉/精确文本
- php - 如何使用 Laravel 5.* 获取数据类型的绑定
- php - 在布尔值中调用成员函数 getTimestamp()