C++11 中的模板模板错误

Template template in c++11 error

我一直在阅读 "C++ Templates, The complete guide" 的第 5 章,我已经看到了 "template template" 模板的概念,所以自己尝试了。

在模板 class 中,我这样声明我的模板:

template <typename TipoClave, typename TipoDato,
         template <class Elem, class Alloc = allocator<Elem>> class Lista = vector>

这行得通。当我尝试使用与默认容器不同的容器时,我的问题就来了。

我的class如下:

class Tabla
{
public:
    struct Celda {
        TipoClave clave;
        TipoDato dato;
    };

    Tabla(unsigned tam)
    {
        t.resize(tam);
    }

///< Some other functions

private:
    typedef Lista<Celda> ListaDatos; 
    Lista<ListaDatos> t;
};

然后,当我尝试像这样从主程序中使用它时:

int main (void)
{
    Tabla<string,Alumno,array> tabla(200);
    ///< Some stuff

    return 0;
}

但是这一行 Tabla<string,Alumno,array> tabla(200); 没有编译,给我一个错误:

test_tabla_t.cpp: In function ‘int main()’: test_tabla_t.cpp:20:27: error: type/value mismatch at argument 3 in template parameter list for ‘template class Lista> class Tabla’ Tabla tabla(200);

我试过使用Tabla<string,Alumno,vector> tabla(200);,而且有效,所以我不知道如何解决这个错误。

假设您正在尝试使用 std::array,它不需要分配器模板参数。它的第二个参数是数组的大小。

template< 
    class T, 
    std::size_t N 
> struct array;

您没有提到您对 C++ 的经验如何,但是由于您想要了解更多,我会说我已经使用 C++ 将近十年了,并且一只手可以指望这个数字我使用模板模板参数的次数。

在这种情况下,您希望 Lista 成为 "something that acts like a sequence container[1]",您可能希望阅读有关概念 [2] 的内容,这可能会使其成为 C++20。它们允许您告诉编译器您希望模板参数具有的接口。

同时,将 Lista 声明为普通模板参数可能更容易。

[1] http://en.cppreference.com/w/cpp/concept/SequenceContainer
[2] https://en.wikipedia.org/wiki/Concepts_(C%2B%2B)