65.9K
CodeProject is changing. Read more.
Home

Usage of '_HAS_CPP0X' macro in Visual C++ compiler

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.67/5 (3 votes)

Jan 16, 2012

CPOL
viewsIcon

34624

Usage of '_HAS_CPP0X' macro in Visual C++ compiler

Take a scenario where we are coding in Microsoft's Visual Studio VC++ 16.0 compiler (which supports many of the C++11 features). We want to take advantage of these new features and at the same time the code should not break with older VC++ versions (which has no C++11 support). This tip shows a possible way of doing it. ========================================== It's simple. Starting from Visual Studio's VC++ 16.0 version compiler, we have a macro '_HAS_CPP0X', which can be utilized for this purpose. Here are a few examples:
void SomeFunction(int i){ } 

void SomeFunction(char* ch) { } 

void main()
{
        // Example 1
#ifdef _HAS_CPP0X
	SomeFunction(nullptr); // Take the advantage of nullptr
#else 
	SomeFunction((char*)NULL); // Hmmm...we have to go for typecasting
#endif

       // Example 2
         struct M { double x; };
	double pi = 3.14;
	const M* m = new M();
#ifdef _HAS_CPP0X
	decltype( (m->x) ) piRef = pi; // Let the compiler decide its type
#else
	double& piRef = pi;
#endif

        // Example 3
        map< int, map<int,int> > _Map;
#ifdef _HAS_CPP0X
	auto itr1 = _Map.cbegin(); // no need for typing drudgery
#else
	map<int, map<int,int>>::const_iterator itr1 = _Map.begin(); 
#endif
}
We can cook up many more examples.