C ++将tempate typename类作为函数参数传递

时间:2015-05-18 06:26:30

标签: c++ templates parameter-passing typename

我需要将模板类作为参数传递给函数,但是我可以检索函数内部的typename来初始化时态变量

该类声明如下:

template <typename Type> class ListIndex_Linked

这里是main中的类的inicialization和函数的调用

ListIndex_Linked<std::string> L;
insertion(L);

以及我正在尝试做什么

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++ )
        {

        }
    }
}

但是我收到了这个错误:

error: 'list' is not a template
void insertion( list<Type>& L )
             ^

提前感谢您的帮助

3 个答案:

答案 0 :(得分:6)

您未正确将'left'声明为list

template template parameter

参考:http://en.cppreference.com/w/cpp/language/template_parameters

答案 1 :(得分:3)

如果ListIndex_Linked仅适用于template <typename Type> void insertion(ListIndex_Linked<Type>& L) { ... } ,那么您可以将其作为模板编写,如果列表的模板参数:

template<template<class> class List, class Type>
void insertion(const List<Type>& L)
{
  ...
}

否则,您可以使用模板模板参数:

$inserted_transport_id

答案 2 :(得分:1)

另一种方法是使用auto不授权Type

template <typename Container>
void insertion(Container& L ) 
{
    auto& temp = L.get(0); 
    {
        int max = L.numElem();
        for ( int i = 1, ; i < max; i++ )
        {

        }
    }
}

typedef内部Container可能会有所帮助,例如

typename Container::reference temp = L.get(0); // or Container::value_type&

需要以下内容:

template <typename Type>
class ListIndex_Linked
{
public:
    using value_type = Type;
    using reference = Type&;
    // ...
    // Your code
};