c++ - 在 C++ 中使用 decltype()、auto 或 RTTI 进行类型相等性测试? Boost 有这个功能吗?

标签 c++ sql rtti type-inference decltype

我正在编写一些代码来将 C++ 类型转换为适合 SQL 数据库的类型。我想识别类型,然后根据它是什么,生成适当的 SQL 代码。我不确定在这方面使用 RTTI、auto 或 decltype 究竟能做什么。我有一些想法,但我不确定它们是否可行。

例如(我知道以下可能不是有效的 C++,我只是想说明一下):

if (decltype(some_var) == int) { do_stuff(); }

if (decltype(some_var) == decltype(1) { do_stuff(); }

switch(decltype(some_var)) {
    case int:
        do_int_stuff();
        break;
    case string;
        do_string_stuff();
        break;
    case bool;
        do_bool_stuff();
        break;
}

string get_func_y(int var) {
    ...
    return my_string;
}

string get_func_y(string var) {
    ...
    return my_string;
}

string get_func_y(bool var) {
    ...
    return my_string;
}

...
string SQL = get_func_y(some_var);

任何这些看起来都行得通,或者有人对如何解决这个问题有建议吗?提前感谢您的任何意见。

最佳答案

您可以使用一个简单的元编程函数来确定(在编译时)两种类型是否相同:

template <typename T, typename U>
struct same_type 
{
   static const bool value = false;
};
template <typename T>
struct same_type< T, T >
{
   static const bool value = true;
};

这是否真的对您的程序有帮助是另一个问题。我会选择简单的函数重载解决方案。

关于c++ - 在 C++ 中使用 decltype()、auto 或 RTTI 进行类型相等性测试? Boost 有这个功能吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3450327/

相关文章:

c++ - 如何实现两个可以相互访问的结构体?

c++ - Boost MPL 占位符和 Lambda

php - MySQL INNER JOIN 复制一列

mysql - 数据库设计 : Associating tables of variable types

c++ - C++ 中的 RTTI 和可移植性

c++ - 如何在同一个立体窗口中并排显示 2 个网络摄像头视频?

c++ - 在 C++ 中,我可以将什么用作 int 数组中的标志?

sql - 给定子网范围和 IP 列表,选择 IP 所在的所有行

c++ - 对 RTTI raw_name() 的好奇心

delphi - 如何获取TRTTIParamter的默认值