2

I'm having a Class called User.

I would like to write a function which gets me all entries of the table User from db like this:

getObectList(type aType)
{
...
select * from aType.name
...
}

and call it like getObjectList(typeof(User))

Is something like this possible in c++?

Baum mit Augen
  • 49,044
  • 25
  • 144
  • 182
helmut1978
  • 417
  • 6
  • 17
  • yes. a template will do this for you as long as each type of aType has a method called name() that returns a string containing the table name. – Richard Hodges May 09 '15 at 12:15
  • The 3rd answer down (not the accepted one) on this question does what you want I believe http://stackoverflow.com/questions/351845/finding-the-type-of-an-object-in-c – Kvothe May 09 '15 at 12:16
  • 1
    You're trying to do something _very_ inflexible: I doubt it's a good idea. Why not call it like `getObjectList(user_table)` where `user_table` is a string (or some object representing a table)? –  May 09 '15 at 12:27

2 Answers2

0

You should check out <typeinfo> header, there are some methods there which might be able to help you.

Example:

#include <typeinfo>

class Foo { };

int main() {
    Foo foo;
    string s = typeid(foo).name();
}

Live example

Have in mind, that output may differ when you use other compilers etc. since it's implementation-detail how to implement naming for types.

To circumvent this, you coul do some testing at initialization for used types and store results of name() or hash_code() methods of used types and then just check it at runtime. This way you get compiler-independent solution.

RippeR
  • 1,472
  • 1
  • 12
  • 23
-1

typeof (expression) is an extension provided by gcc and Clang. It is exactly the same as using the type itself, so if you write

int x;
typeof (x) y;

the second declaration is exactly the same as writing int y. typeof will never have any effect at runtime; the type it returns is always determined at compile time.

You cannot pass a type to a function. Whether you type it directly or by using typeof () doesn't make a difference.

gnasher729
  • 51,477
  • 5
  • 75
  • 98
  • 4
    Its much better to use decltype, which is standard in C++11, not some extensions in specific compiler. Though i think it's not what author wanted. – RippeR May 09 '15 at 12:20