What differences, if any, between C++03 and C++11

2019-01-09 23:38发布

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()
{ 
    //???
} 

8条回答
我命由我不由天
2楼-- · 2019-01-10 00:09

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):

 int IsCxx03()
 {
   auto x = (int *)0;
   return ((int)(x+1) != 1);
}
查看更多
霸刀☆藐视天下
3楼-- · 2019-01-10 00:12

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).

template< template< class > class > char f( int );
template< class > char (&f(...))[2];

template< class > class A {
  char i[ sizeof f< A >(0) ];
};

bool isCpp0x() {
  return sizeof( A<int> ) == 1;
}
查看更多
登录 后发表回答