内联命名空间(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)
发布评论