簡體   English   中英

具有 cv 和 ref 類型的模板特化

[英]Template specialization with cv and ref types

為了理解元編程,我創建了一個簡單的例子:

template <class T> struct add_cref      { typedef T const& type; };
// template <class T> struct add_cref<T&>   { typedef T const& type; };


std::cout << std::boolalpha
    << std::is_same<add_cref<int>::type, int const&>::value << std::endl
    << std::is_same<add_cref<int&>::type, int const&>::value << std::endl
    << std::is_same<add_cref<const int>::type, int const&>::value << std::endl
    << std::is_same<add_cref<int const&>::type, int const&>::value << std::endl;

結果是:真、假、真、真
當我取消注釋模板規范時,結果如預期(全部為真)

我的問題是,為什么在沒有注釋的情況下第二個是假的,而最后一個是真,而沒有專業化,則兩者都使用專業化。

template <class T> 
struct add_cref { 
    typedef T const& type; 
};

使用類型add_cref<int&>::typeT = int& 然后類型add_cref<int&>::typeint& const &大致相同,這意味着引用int&是 const 而不是整數本身。

編輯:使用類型add_cref<const int&>::typeT = const int& 然后,類型add_cref<const int&>::typeconst int& const &大致相同,這意味着引用本身const int&是 const (編譯器忽略第二個 const )但它指的是const int 這意味着add_cref<const int&>::type必須是const int& ,即使沒有專門化。

專業化:

template <class T> 
struct add_cref<T&> { 
   typedef T const& type; 
}; 

對於add_cref<int&>因為在這個專業化中T&=int&然后T=int 結果, T const&type變為int const &

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM