Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Namespace alias in c++

I use c++11 while I need some classes from c++17 library. When using boost from which classes were added I wish to do the following:

#if __cplusplus < CPP17
using std::any = boost::any;  
#endif

Such alias is not allowed. Also extending the std namespace causes undefined behaviour. I wish my code to look the same regardles of the c++ version. Is there a clear way?

like image 461
Ariel Avatar asked Jan 02 '17 01:01

Ariel


2 Answers

The clear way is to add a customized name for it.

#if __cplusplus < CPP17
using my_any = boost::any;
#else
using my_any = std::any;    
#endif

// using my_any...
like image 134
songyuanyao Avatar answered Nov 07 '22 02:11

songyuanyao


It seems that you're attempting to create a type alias within a namespace. The corect syntax for that is:

namespace namespace_name {
    using any = boost::any;
}

However, the standard disallows adding definitions (there are exceptions for template specializations) into std namespace, so if you tried to define std::any, the behaviour of your program will be undefined.

Using any namespace, including the global one is OK, but not the ones reserved to the implementation, which includes std and its subnamespaces.

like image 6
eerorika Avatar answered Nov 07 '22 02:11

eerorika