It is possible to write a function, which, when compiled with a C compiler will return 0, and when compiled with a C++ compiler, will return 1 (the trivial sulution with
#ifdef __cplusplus
is not interesting).
For example:
int isCPP()
{
return sizeof(char) == sizeof 'c';
}
Of course, the above will work only if sizeof (char)
isn't the same as sizeof (int)
Another, more portable solution is something like this:
int isCPP()
{
typedef int T;
{
struct T
{
int a[2];
};
return sizeof(T) == sizeof(struct T);
}
}
I am not sure if the examples are 100% correct, but you get the idea. I believe there are other ways to write the same function too.
What differences, if any, between C++03 and C++11 can be detected at run-time? In other words, is it possible to write a similar function which would return a boolean value indicating whether it is compiled by a conforming C++03 compiler or a C++11 compiler?
bool isCpp11()
{
//???
}
This isn't quite a correct example, but it's an interesting example that can distinguish C vs. C++0x (it's invalid C++03 though):
Though not so concise... In current C++, class template name itself is interpreted as a type name (not a template name) in that class template's scope. On the other hand, class template name can be used as a template name in C++0x(N3290 14.6.1/1).