Reputation: 3482
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.
Upvotes: 2
Views: 1623
Reputation: 57066
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.
Upvotes: 1
Reputation: 208446
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.
Upvotes: 5
Reputation: 13431
Your last option of using simple function overloading should work fine.
Upvotes: 4