https://blog.csdn.net/qq_35976351/article/details/86436193
基础用法
命名空间说明符
最常用的,,std::cout之类的,或者是自定义的命名空间。
类作用符
这是第二个基础的用法,用于类函数定义使用的
class C {
public:
void foo();
};
void C::foo() {
/*...*/
}
全局变量说明符
当局部变量和全局变量重名的时候,使用::来显式说明全局变量。
#include <iostream>
static int n = 10;
int main() {
int n = 5;
std::cout << n << std::endl; // 输出5
std::cout << ::n << std::endl; // 输出10
return 0;
}
模板元编程中的高级用法
下面这些内容参考自《C++模板元编程实战》,作者李伟。
模板元编程中,::可以返回类型甚至是模板,具体参照代码:
#include <iostream>
template <typename T>
struct Fun_ {
using type = T;
};
template <> // 模板特化
struct Fun_<int> {
using type = unsigned int;
};
int main() {
Fun_<long>::type t = 10;
Fun_<int>::type t1 = 10;
return 0;
}
再代码中直接使用域作用符进行类型的说明。
模板也可以作为元函数的输出:
#include <iostream>
#include <type_traits>
template <bool AddOrRemoveRef> struct Fun_;
template <>
struct Fun_<true> {
template <typename T>
using type = std::add_lvalue_reference<T>;
};
template <>
struct Fun_<false> {
template <typename T>
using type = std::remove_reference<T>;
};
// 注意这里的高级用法
template <typename T>
template <bool AddOrRemoveRef>
using Fun = typename Fun_<AddOrRemoveRef>::template type<T>;
// 即使是有别名,还是需要显式说明模板
template <typename T>
using Res_ = Fun<false>;
int main() {
Res_<int&>::type h = 3;
std::cout << h << std::endl;
return 0;
}