views:

267

answers:

3

Hello, I have question regarding macros. How could I cast through macro a template class to normal class. In example:

#define RUNTIME_CLASS(class_name) ((CRuntimeClass*)(&class##class_name))

template<typename T> A {};

if (RUNTIME_CLASS(A));

I know that this code woun't compile because it will not see template bit. But I don't understand the actual macro. the return of it looks like (CRuntimeClass*)(&classA)

Why ## concatenate makes class + A ? and how preprocessor understands such notation? Thanks ALOT!

A: 

That's just what it does, ## concatenates a string and a parameter passed into your #define.

Blindy
+1  A: 

Maybe where you took the macro all the class names are starting with "class" and the macro expects only the second part of the name, what comes after "class".

grigy
+1  A: 

I don't understand the question.

First - I don't understand why you'd want to cast a template class into a normal class. The way to convert a template class into a concrete class is to supply the template parameters. Without those parameters, the template class has not been fully defined, and therefore simply cannot be used.

In a way, a template is a function that is evaluated at compile time in order to define a class/function. Without the parameters, trying to treat the template as a class is like trying to treat an unevaluated function as a number.

As already mentioned, "##" is a token concatenating preprocessor operator. If you aren't expecting that, I don't understand why you are writing "##".

Is this something to do with name mangling?

Steve314