Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ template method: Why Node<int> is fine, but not Node<float>?

Tags:

c++

templates

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;
}
like image 493
Lavanti Avatar asked May 18 '16 05:05

Lavanti


People also ask

What does template typename t mean?

" 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.

Why using template C++?

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.

What is template what is the need of template declare a template class?

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++.

How function template are implemented?

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.


2 Answers

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);
like image 129
songyuanyao Avatar answered Sep 29 '22 11:09

songyuanyao


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)
like image 36
Jarod42 Avatar answered Sep 29 '22 12:09

Jarod42