I got this template:
template <typename T>
struct List {
struct node {
T key;
node* prev;
node* next;
};
node* first = nullptr;
node* last = nullptr;
// functions
};
I need to create a function OUTSIDE of the struct that takes a List as a parameter. I tried something but doesnt work
void palindrome(List<typename T> L)
CodePudding user response:
Your List
is a class template (not template class / struct, it is not a class). You cannot pass a template to a function. You can only pass objects of some type to a function. List
is not a type. List<double>
for example is a type. So you could do for example:
void palindrome(List<double> L);
However, I suppose you want to pass any instantation of List
to the function, eg a List<double>
or a List<int>
etc. Then you can make the function itself a function template:
template <typename T>
template void palindrome(List<T> l);
Note that this is not a function that accepts any instanatiation of List
. It is just a template, and calling it with a List<int>
or a List<double>
will instantiate two distinct functions.
Sometimes it is simpler to be more generic, and you can do as well
template <typename L>
template void palindrome(L l);
CodePudding user response:
In your function the typename T is unbound. The compiler has no idea what to do with that. You need to create a template function like this:
template<typename T> void palindrome(List<T> t) {}
The compiler will then deduce the typename T when you use the function.
CodePudding user response:
List
is a class template which is diferent from a class type. A class type would be List<int>
or a List<double>
etc.
You can make palindrome
a function template that has a parameter of type List<T>
for some type T
, as shown below.
//a function template that has parameter of type List<T>
template<typename T>
void palindrome(List<T> L)
{
std::cout<<"palindrome called"<<std::endl;
}
int main()
{
List<int> l1;
//call
palindrome(l1);//T will be deduced to int
List<double> l2;
//call
palindrome(l2); //T will be deduced to double
return 0;
}