Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
473 views
in Technique[技术] by (71.8m points)

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

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...