Namespace alias in c++

二次信任 提交于 2021-02-20 06:26:16


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;  

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?


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

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

// using my_any...


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.


I don't see the big deal with undefined behavior worries. You use an #if to check for C++17 already, and you know there's no any before that. If you really want this, I say go for it, and place the alias in std if it's earlier than C++17.

At the end of the day, helper functions/classes/etc will likely be placed in another namespace or prefixed with __ because that's available to standard libraries. I don't think any implementation of pre-C++17 exports any in std.

There's no other way. Just ignore "undefined behavior" and go for it if it works. There's nothing magical about it ruining your code; worst that can happen is a bad std implementation will conflict and fail to compile when you define the alias. Some people overblow undefined behavior issues in my opinion.