Member Function Templates

Template specialization for member function templates

Is it possible to specialize a member function template? How would I do that?

Illustration representing computer hardware

Yes, it is possible to create specializations of member function templates, just like you can for regular function templates. This allows you to provide a different implementation of the function for specific template arguments.

Here's an example:

#include <iostream>

class MyClass {
public:
  template <typename T>
  void func(T x) {
    std::cout << "Generic implementation: "
      << x << std::endl;
  }
};

template <>
void MyClass::func<int>(int x) {
  std::cout << "Specialization for int: "
    << x << std::endl;
}

int main() {
  MyClass obj;
  
  // calls the int specialization
  obj.func(42);
  
  // calls the generic implementation
  obj.func(3.14);
}
Specialization for int: 42
Generic implementation: 3.14

In this code, we have a generic implementation of MyClass::func that works for any type T. But we also provide a specialization of MyClass::func specifically for int.

To specialize the member function template, we use the template <> syntax, followed by the full signature of the specialization, including the class name and template arguments (void MyClass::func<int>(int x)).

When we call obj.func(42), it invokes the int specialization, because 42 is an int. But when we call obj.func(3.14), it uses the generic implementation, because there's no specialization for double.

Specializations let you optimize the function for certain types, handle special cases, or provide totally different implementations based on the template arguments. They're a key part of the power and flexibility of C++ templates.

This Question is from the Lesson:

Member Function Templates

Learn how to create and use member function templates in classes and structs, including syntax, instantiation, and advanced techniques

Answers to questions are automatically generated and may not have been reviewed.

This Question is from the Lesson:

Member Function Templates

Learn how to create and use member function templates in classes and structs, including syntax, instantiation, and advanced techniques

A computer programmer
Part of the course:

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Free, unlimited access

This course includes:

  • 125 Lessons
  • 550+ Code Samples
  • 96% Positive Reviews
  • Regularly Updated
  • Help and FAQ
Free, Unlimited Access

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Screenshot from Warhammer: Total War
Screenshot from Tomb Raider
Screenshot from Jedi: Fallen Order
Contact|Privacy Policy|Terms of Use
Copyright © 2024 - All Rights Reserved