【C++】嵌套命名空间和内联命名空间(c++11)

编程入门 行业动态 更新时间:2024-10-24 01:48:33

【C++】嵌套命名空间和<a href=https://www.elefans.com/category/jswz/34/1735939.html style=内联命名空间(c++11)"/>

【C++】嵌套命名空间和内联命名空间(c++11)

嵌套命名空间

【用法】

namespace test1::test2::test3 {int TestMethod() {return 0;}
}

等价于:

namespace test1 {namespace test2 {namespace test3 {int TestMethod() {return 0;}}}
}

【作用】
代码更简洁美观

内联命名空间

【用法】
namespace关键字前加inline关键字:

namespace test {inline namespace V1 {int TestMethod() {return 1;}}
}

调用时可以直接通过以下方式调用,省略子namespace的名字:

test::TestMethod();

【特性】
内联命名空间中的名字可以被外层命名空间直接使用,无需前缀。
【使用场景】
当namespace中加入新特性时,无需使用者修改代码。如:当V1升级为V2时,使用inline修饰V2的命名空间,使用者无需再修改代码。
原来定义的namespace:

namespace test {namespace V1 {int TestMethod() {return 1;}}
}

新版本的namespace:

namespace test {inline namespace V1 {int TestMethod() {return 1;}}namespace V2 {int TestMethod() {return 1;}}
}

前后两个版本使用者都可以通过test::TestMethod()调用V1中的TestMethod方法。

更多推荐

【C++】嵌套命名空间和内联命名空间(c++11)

本文发布于:2023-11-16 17:44:48,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1630071.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:内联   嵌套   空间

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!