I rarely use templates. I don't know why I see a build error in the below code for the push
method of Node<float>
Build Error is: No matching function to call push.
Node<int>*
push method is fine though.
Node<float>* head1 = NULL;
push(&head1, 1);
template <typename T>
struct Node {
T data;
Node* next;
};
template <typename T>
void push(Node<T>** head, T data) {
Node<T>* tmp = *head;
Node<T>* newNode = NULL; //createNode(data);
if (tmp == NULL) {
*head = newNode;
}
else {
while (tmp->next)
tmp=tmp->next;
tmp->next = newNode;
}
}
int main(int argc, const char * argv[]) {
Node<float>* head1 = NULL;
push(&head1, 1);
Node<int>* head = NULL;
push(&head, 1);
return 0;
}
" typename " is a keyword in the C++ programming language used when writing templates. It is used for specifying that a dependent name in a template definition or declaration is a type.
Templates are very useful when implementing generic constructs like vectors, stacks, lists, queues which can be used with any arbitrary type. C++ templates provide a way to re-use source code as opposed to inheritance and composition which provide a way to re-use object code.
Templates in c++ is defined as a blueprint or formula for creating a generic class or a function. To simply put, you can create a single function or single class to work with different data types using templates. C++ template is also known as generic functions or classes which is a very powerful feature in C++.
A function template starts with the keyword template followed by template parameter(s) inside <> which is followed by the function definition. In the above code, T is a template argument that accepts different data types ( int , float , etc.), and typename is a keyword.
For push(&head1, 1);
, the type of &head1
is Node<float>**
, and type of 1
is int
, then type deduction for template parameter T
will fail with conflicting types (float
vs. int
).
You could make the types match:
push(&head1, 1.0f);
or explicitly specify the template argument by float
, and 1
will be casted to float
.
push<float>(&head1, 1);
As alternative, you may do the second argument non deducible:
template <typename T> struct non_deducible
{
using type = T;
};
template <typename T> using non_deducible_t = non_deducible<T>::type
template <typename T>
void push(Node<T>** head, non_deducible_t<T> data)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With