Type equality test w/ decltype(), auto, or RTTI in C++? Does Boost have something for this?

心已入冬 提交于 2019-11-27 08:17:38

问题


I'm writing some code to translate a C++ type to an appropriate type for a SQL DB. I want to identify the type, and then depending on what it is, produce the appropriate SQL code. I'm not sure exactly what can be done in this regard by using RTTI, auto, or decltype. I have some ideas but I'm not sure if they're workable.

For instance (I know the following may not be valid C++, I'm just trying to get the idea across):

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

or

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

or

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

or

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);

Any of this look like it would work, or does anyone have advice on how to go about this? Thanks ahead of time for any input you may have.


回答1:


You can use a simple metaprogramming function to determine (at compile time) whether two types are the same:

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;
};

Whether that actually helps you with your program or not is a different question. I would just go for the simple function overload solution.




回答2:


Your last option of using simple function overloading should work fine.




回答3:


In C++, variables and functions have static types. The only possible confusion, other than misusing casts, is whether a pointer to a base class is pointing to a base or some derived. This means that your decltypes are going to be useless as conditions (except for class derivation), since they will have a constant answer.

Overloaded functions work well with static typing. Use them.



来源:https://stackoverflow.com/questions/3450327/type-equality-test-w-decltype-auto-or-rtti-in-c-does-boost-have-somethin

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!