C ++ Passing tempate typename class as function parameter
I need to pass the template class as a parameter to a function, but I can get the type name inside the function to initialize a temporary variable
the class is declared like this:
template <typename Type> class ListIndex_Linked
this implies the initialization of the class in the main and the call of the function
ListIndex_Linked<std::string> L;
insertion(L);
and what i am trying to do
template <class list <typename Type>>
void insertion( list<Type>& L )
{
Type& temp = L.get(0);
{
int max = L.numElem();
for ( int i = 1, ; i < max; i++ )
{
}
}
}
but I am getting this error:
error: 'list' is not a template
void insertion( list<Type>& L )
^
in advance for help
source to share
You are not announcing list
how template template parameter
correctly.
template <template <typename> class list, typename Type>
void insertion( list<Type>& L )
{
...
}
Link: http://en.cppreference.com/w/cpp/language/template_parameters
source to share
If insertion
should only work with ListIndex_Linked
, you can write it as a template in terms if the list template parameter is:
template <typename Type>
void insertion(ListIndex_Linked<Type>& L)
{
...
}
Otherwise, you can use the template template parameters:
template<template<class> class List, class Type>
void insertion(const List<Type>& L)
{
...
}
source to share
Another way is to use auto
for non-mandate Type
:
template <typename Container>
void insertion(Container& L )
{
auto& temp = L.get(0);
{
int max = L.numElem();
for ( int i = 1, ; i < max; i++ )
{
}
}
}
There is also typedef
inside Container
that can help, something like
typename Container::reference temp = L.get(0); // or Container::value_type&
which requires something like:
template <typename Type>
class ListIndex_Linked
{
public:
using value_type = Type;
using reference = Type&;
// ...
// Your code
};
source to share