C++域作用符及其高级用法

基础用法

命名空间说明符

最常用的,,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;
}
  • 0
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值