Home  >  Article  >  Backend Development  >  Template specialization and template partial specialization in C++?

Template specialization and template partial specialization in C++?

WBOY
WBOYOriginal
2024-05-08 17:33:01859browse

Template specialization and partial specialization are unique mechanisms in C. Template specializations provide specific implementations for template parameters of specific types, while template partial specializations allow templates to be typed based on some of the template parameters, making their use more flexible. Template specializations use template syntax, while template partial specializations use template class MyClass syntax.

Template specialization and template partial specialization in C++?

Template specialization and template partial specialization in C

Template specialization

Template specialization refers to explicitly providing a specific template implementation for a specific type of template parameter. The syntax is as follows:

template <>
class MyClass<MyType> {
  // 特化代码
};

Example:

template <typename T>
class MyClass {
  T value;

public:
  MyClass(T v) : value(v) {}
  T getValue() { return value; }
};

template <>
class MyClass<int> {
  int value;

public:
  MyClass(int v) : value(v) {}
  int getValue() { return value * 2; }
};

int main() {
  MyClass<string> strObj("Hello");
  cout << strObj.getValue() << endl;

  MyClass<int> intObj(5);
  cout << intObj.getValue() << endl;
}

Output:

Hello
10

Template partial specialization

Template partial specialization is a special template specialization that allows templates to be typed based on part of the template parameters. The syntax is as follows:

template <typename T, typename U>
class MyClass {
  // ...
};

template <typename T>
class MyClass<T, T> {
  // 偏特化代码
};

Example:

template <typename T, typename U>
class MyClass {
  T value1;
  U value2;

public:
  MyClass(T v1, U v2) : value1(v1), value2(v2) {}
  T getValue1() { return value1; }
  U getValue2() { return value2; }
};

template <typename T>
class MyClass<T, T> {
public:
  MyClass(T v) : value1(v), value2(v) {}
  T getValue1() { return value1; }
  T getValue2() { return value2; }
};

int main() {
  MyClass<string, int> strIntObj("Hello", 5);
  cout << strIntObj.getValue1() << ", " << strIntObj.getValue2() << endl;

  MyClass<int> intObj(10);
  cout << intObj.getValue1() << ", " << intObj.getValue2() << endl;
}

Output:

Hello, 5
10, 10

The above is the detailed content of Template specialization and template partial specialization in C++?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn