C ++ namespace alias

I am using C ++ 11, while I need some classes from the C ++ 17 library. When using boost, from which the classes were added, I want to do the following:

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

Such an alias is not allowed. Additionally, the std namespace extension causes undefined behavior . I want my code to look the same with respect to the C ++ version. Is there a clear way?

+7
c ++ namespaces c ++ 11
source share
3 answers

A 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... 
+6
source share

It seems like you are trying to create a type alias in a namespace. The corect syntax for this is:

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

However, the standard prohibits adding definitions (there are exceptions for specialized templates) to the std , so if you try to define std::any , the behavior of your program will be undefined.

The use of any namespace, including global, is OK, but not those reserved for an implementation that includes std and its subheadings.

+6
source share

I do not see a big problem with undefined behavior. You use #if to check in C ++ 17, and you know any there before. If you really want this, I say, go after it and put an alias in std if it is earlier than C ++ 17.

At the end of the day, the helper functions / classes / etc will most likely be placed in another namespace or with the __ prefix, as this is available for standard libraries. I do not think that the pre-C ++ 17 implementation exports any to std.

There is no other way. Just ignore the "undefined behavior" and go if that works. There is nothing magical about destroying your code; the worst that can happen is the failed implementation of std, and it does not compile when defining an alias. In my opinion, some people face undefined behavior problems.

0
source share

All Articles