喜歡這篇文章嗎?喜歡的話去看博主的置頂博客,即可依據分類找到此文章的原版得到更好的體驗,
圖片及代碼顯示的問題,筆者深感抱歉,想要更好的體驗去原博文即可。
title: Boost 源碼分析筆記6 - remove_reference
mathjax: true
date: 2020-03-17 16:27:47
categories: [c++筆記,Boost源碼分析筆記]
tags: [c++筆記,Boost源碼分析筆記]
keywords: [c++筆記,Boost源碼分析筆記]
remove_reference
這個名字就很棒,就是移除引用的意思。同樣他也是模版元技術,他先將所有的類型映射爲自己,然後通過模版偏特化的方式將那些引用映射爲本身。這裏有一個c++的特性即下面代碼
這個代碼看懂的人應該不多了。
#include <iostream>
void f(int& x) { std::cout << "&" << std::endl; }
void f(int&& x) { std::cout << "&&" << std::endl; }
int main() {
int a = 1, b = 2, c = 3, d = 4;
f(a);
f(b);
f(c);
f(d);
f(1);
f(2);
f(3);
f(4);
}
這裏的&&就是右值引用的意思,所以輸出是
&
&
&
&
&&
&&
&&
&&
然後我們來看源碼
namespace detail{
//
// We can't filter out rvalue_references at the same level as
// references or we get ambiguities from msvc:
//
template <class T>
struct remove_rvalue_ref
{
typedef T type;
};
#ifndef BOOST_NO_CXX11_RVALUE_REFERENCES
template <class T>
struct remove_rvalue_ref<T&&>
{
typedef T type;
};
#endif
} // namespace detail
template <class T> struct remove_reference{ typedef typename boost::detail::remove_rvalue_ref<T>::type type; };
template <class T> struct remove_reference<T&>{ typedef T type; };
#if defined(BOOST_ILLEGAL_CV_REFERENCES)
// these are illegal specialisations; cv-qualifies applied to
// references have no effect according to [8.3.2p1],
// C++ Builder requires them though as it treats cv-qualified
// references as distinct types...
template <class T> struct remove_reference<T&const>{ typedef T type; };
template <class T> struct remove_reference<T&volatile>{ typedef T type; };
template <class T> struct remove_reference<T&const volatile>{ typedef T type; };
#endif
同樣的我們使用模版元技術,將引用就消除了。