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