類別樣板的預設引數

類別樣板可以有型別或值的參數的預設引數。指定預設的引數等 (=) 符號後面的型別名稱或值。用於多個樣板引數,在第一個預設的引數之後的所有引數必須有預設引數。當宣告樣板類別物件以預設引數,省略引數以接受預設的引數。如果不有任何非預設引數,不會省略空括弧。

多重宣告的範本不能超過一次指定預設的引數。下列程式碼將示範錯誤:

template <class T = long> class A;
template <class T = long> class A { /* . . . */ }; // Generates C4348.

範例

在下列範例中,陣列類別樣板定義為預設型別int陣列元素和指定大小的範本參數的預設值。

// template_default_arg.cpp
// compile with: /EHsc
#include <iostream>
using namespace std;

template <class T = int, int size = 10> class Array
{
   T* array;
public:
   Array()
   {
      array = new T[size];
      memset(array, 0, size * sizeof(T));
   }
   T& operator[](int i)
   {
      return *(array + i);
   }
   const int Length() { return size; }
   void print()
   {
      for (int i = 0; i < size; i++)
      {
         cout << (*this)[i] << " ";
      }
      cout << endl;
   }
};

int main()
{
   // Explicitly specify the template arguments:
   Array<char, 26> ac;
   for (int i = 0; i < ac.Length(); i++)
   {
      ac[i] = 'A' + i;
   }
   ac.print();
   
   // Accept the default template arguments:
   Array<> a; // You must include the angle brackets.
   for (int i = 0; i < a.Length(); i++)
   {
      a[i] = i*10;
   }
   a.print();
}
  

請參閱

參考

預設引數