Using Template Parameters in Constructors

Can I use template parameters in the constructor of a class template?

Yes, you can definitely use template parameters in the constructor of a class template. In fact, this is a common and useful practice in C++ template programming.

It allows you to create constructors that work with the types specified when the template is instantiated.

Here's an example to illustrate how you can use template parameters in constructors:

#include <iostream>
#include <string>

template <typename T>
class Container {
 private:
  T value;

 public:
  // Constructor using the template parameter T
  Container(T initialValue)
    : value{initialValue} {
    std::cout << "Constructed with value: "
      << value << '\n';
  }

  // Another constructor using a different type
  template <typename U>
  Container(U differentType)
    : value{static_cast<T>(differentType)} {
    std::cout << "Constructed with converted value: "
      << value << '\n';
  }

  void Display() const {
    std::cout << "Container holds: "
      << value << '\n';
  }
};

int main() {
  Container<int> intContainer{42};
  intContainer.Display();

  Container<double> doubleContainer{3.14};
  doubleContainer.Display();

  Container<std::string> stringContainer{"Hello"};
  stringContainer.Display();

  // Using the second constructor
  Container<int> convertedContainer{3.14};
  convertedContainer.Display();
}
Constructed with value: 42
Container holds: 42
Constructed with value: 3.14
Container holds: 3.14
Constructed with converted value: Hello
Container holds: Hello
Constructed with converted value: 3
Container holds: 3

In this example, we've defined two constructors:

  1. The first constructor takes a parameter of type T, which is the template parameter of the class. This allows us to construct the object with a value of the same type as the container is instantiated with.
  2. The second constructor is itself a template function. It takes a parameter of type U, which can be different from T. This constructor attempts to convert the input to type T using static_cast. This allows for more flexible instantiation, where the input type doesn't have to exactly match the container's type.

Using template parameters in constructors gives you a lot of flexibility. You can:

  • Ensure type safety by using the exact type the template is instantiated with.
  • Provide conversion constructors for different types.
  • Implement perfect forwarding to construct contained objects efficiently.

Remember, when using template parameters in constructors, the usual rules of template type deduction apply. If you're using C++17 or later, you can take advantage of class template argument deduction (CTAD) to simplify the syntax when creating objects.

Class Templates

Learn how templates can be used to create multiple classes from a single blueprint

Questions & Answers

Answers are generated by AI models and may not have been reviewed. Be mindful when running any code on your device.

Partial Specialization of Class Templates
Is it possible to partially specialize a class template?
Compile-Time Polymorphism with Templates
Can I use templates to implement compile-time polymorphism?
Creating Templates with Variable Number of Parameters
How can I create a template that works with an arbitrary number of type parameters?
Default Values for Non-Type Template Parameters
Is it possible to have default values for non-type template parameters?
Constraining Template Arguments
How can I create a template that only accepts certain types of arguments?
Typename vs Class in Template Declarations
What's the difference between typename and class in template parameter declarations?
Creating Class Templates with Multiple Types
How can I create a class template that works with both primitive types and user-defined types?
Best Practices for Naming Template Parameters
What are the best practices for naming template parameters?
Specializing Class Templates
How can I specialize a class template for specific types?
Template Methods in Non-Template Classes
How do I create a template method within a non-template class?
Or Ask your Own Question
Get an immediate answer to your specific question using our AI assistant