簡體   English   中英

模板類問題的部分專業化!

[英]partial specialization of template class issue!

以下代碼使我感到困惑

//partial specialization of vector 
template<class t>
class vector
{....
};
template<class t>
//teacher said that this partial specialization will handle all type of pointers
class vector<t*>
...
};

這讓我很困惑,假設t是char *,因為編譯器將首先尋找完全專業化,因為這里沒有完全專業化,因此將考慮部分專業化。 現在,它將成為部分專業化的char **,因為t是char *,這意味着我們未實現所需的功能。 請以更易理解的方式解釋。

編譯器將始終尋找最專業匹配項(如果存在歧義,將失敗)。

由於char**匹配兩種模式:

char** = T*  (with T = char*)
char** = T   (with T = char**)

而前者則更專業,因此會選擇。 (並且由於char**實際上是指向某個東西的指針,所以我認為“我們沒有實現所需的功能”是錯誤的。)


編輯。

一旦選擇了專業化,所有其他候選人將被淘汰(在匹配階段將不會進行遞歸替換)。 例如,

template<class T> struct A {
  typedef T type;
  static const int value = 0;
};
template<class T> struct A<T*> {
  typedef T type;
  static const int value = 12;
};
template<class T> struct A<T********> {
  typedef T type;
  static const int value = 1024;
};
...
A<char**>::type x;                          // <-- Line X
std::cout << A<char**>::value << std::endl; // <-- Line Y

在X行和Y行,將實例化模板A 您將第一個模板參數指定為char** A期望使用T********T*T 第二個是最佳匹配,因此將選擇template<class T> struct A<T*> 其他兩個將被淘汰。

# FAIL. Not specialized enough. Remove this from consideration.
//  template<class T> struct A {
//    typedef T type;
//    static const int value = 0;
//  };

# WIN. Use with T = char*.
    template<class T> struct A<T*> {
      typedef T type;
      static const int value = 12;
    };

# FAIL. Does not match char**.
// template<class T> struct A<T********> {
//   typedef T type;
//   static const int value = 1024;
// };

執行替換后,它變為

struct A<char**> {
  typedef char* type;
  static const int value = 12;
};

X和Y線將變為

/*A<char**>::type*/ char* x;                       // <-- Line X
std::cout << /*A<char**>::value*/ 12 << std::endl; // <-- Line Y

(注意:

template<class T> class Vector

不是部分專業化,

template<class T> class Vector<T*>

這個是。)

編譯器實例化vector<char*> ,它與以下模板匹配:

template<class T>
class vector<T*> {
  ...
};

為了使該模板生成類vector<char*> ,需要使用T=char實例化它,而這正是編譯器所做的。

當編譯器看到類型為vector<char*> ,將不會使用T=char*實例化模板,因為這將導致錯誤的類型vector<char**> 它將使用T=char代替,這將導致vector<char*> 編譯器使用模板參數,這些參數將給出正確的結果類型。

template<class t>
//teacher said that this partial specialization will handle all type of pointers
class vector<t*>
{
    ...
};

vector<char*> v;

您的困惑來自假設<class t><class t>命名了實例化時給出的完整參數。 而是將參數與<t*>匹配,因此t = char

例如,想象以下專門化:

template <class T> struct Foo {};
template <class T> struct Foo<vector<T> > {}; //specialization for your vector

Foo<vector<int> > f;

再次選擇特殊化,其中vector<int>vector<T>匹配,並且T = int

暫無
暫無

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

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