tags:

views:

148

answers:

5

Is there such macro in C++ (cross-compiler or compiler-specific):

#if isclass(NameSpace::MyClass)

Would be useful. Thank you.

+5  A: 

There is no such thing at the preprocessing stage, so no macro.

However you can have a look at the is_class type traits available in Boost or in C++0x that enable you to take decisions at compile time.

Gregory Pakosz
I think the problem here is that `Namespace::MyClass` has to be declared as something, even if it is not a class?
UncleBens
I would like to include files, depending on knowledge if some classes are already defined.
topright
@topright: But why? There are several ways this could be problematic if you aren't careful.
Dennis Zickefoose
@topright: Then why not just use #include guards?
John Dibling
+8  A: 

No. Preprocessing directives and macros are evaluated by the preprocessor, which completes its tasks before the code is parsed as C++. The preprocessor has no knowledge of classes or namespaces.

James McNellis
+4  A: 

That's not possible, but you could use your include guard constant to verify that the class has been included.

soulmerge
Yes, indeed. But it is not the real solution.
topright
To what problem?
soulmerge
+4  A: 

If you do not care about portability, the __if_exists statement in VC++ meets your needs.

Sherwood Hu
That's it! Thanks. :)
topright
+2  A: 

It sounds to me like it would be better to test if the header file with the class definition you're looking for has been included yet, instead of trying to see if the class exists. It's really easy to check this if you've been implementing the standard of defining a symbol for each header file, as shown:

// myfile.h

#ifndef _MYFILE_H_
#define _MYFILE_H_

// CODE

#endif // _MYFILE_H_

Your best bet though, is to just make sure your header files are being included in the right order in the first place. The easiest way to do this is to have an "overall" header file that in turn includes all the headers you will need in the correct order. Simply include that in each of the source files in your project, and you'll be good to go. This isn't necessarily the best solution, but it is the easiest.

DoctorT
Yes, indeed. I thought about this workaround.
topright