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:
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.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:
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.
Answers to questions are automatically generated and may not have been reviewed.
Learn how templates can be used to create multiple classes from a single blueprint