C++ typename Keyword
Example
Use typename to create a class template:
template <typename T>
class Box {
public:
T value;
Box(T v) {
value = v;
}
};
int main() {
Box<int> intBox(50);
Box<string> strBox("Hello");
cout << intBox.value << "\n";
cout << strBox.value;
return 0;
}
Definition and Usage
The typename keyword declares a type parameter in a template. In template <typename T>, T is a placeholder for a data type, which is chosen when you use the template.
In the example above, T becomes int in Box<int>, and string in Box<string>. You can also write class instead of typename here, like template <class T>. Both mean the same.
typename also has a second, more advanced use: inside a template, it tells the compiler that a name is a type.
Related Pages
Read more about templates in our C++ Templates Tutorial.