Namespace alias in c++

自作多情 提交于 2021-02-20 06:20:06

问题


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?


回答1:


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



回答2:


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.




回答3:


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.



来源:https://stackoverflow.com/questions/41420624/namespace-alias-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!