链接模板与传递 stl 容器的问题

  • 本文关键字:问题 stl 链接 c++
  • 更新时间 :
  • 英文 :


我正在编写下面的代码和错误消息。

template<template <typename...> class container_type>
void test_int(string container_name){
    container_type<int,std::vector> container1;
    container_type<int,std::set> container2;
    container_type<int,std::list> container3;
        ...

主.cpp

test_int<ArrayList>("arraylist"); ---> error
ArrayList<int,std::Vector> test; ---> no error
 ....

编译器说:

test.cpp:17:32: error: type/value mismatch at argument 1 in template 
parameter list for ‘template<class ...> class container_type’
container_type<int,std::vector> container1;
                            ^
test.cpp:17:32: note:   expected a type, got ‘vector’
test.cpp:18:29: error: type/value mismatch at argument 1 in template 
parameter list for ‘template<class ...> class container_type’
container_type<int,std::set> container2;
                         ^
test.cpp:18:29: note:   expected a type, got ‘set’
test.cpp:19:30: error: type/value mismatch at argument 1 in template 
parameter list for ‘template<class ...> class container_type’
container_type<int,std::list> container3;

数组列表

template<typename T,template <typename...> class Container>
class ArrayList : public list<T,Container>
{....
private:
    Container<T> array;

我该如何解决这个问题?容器数组工作正常,逻辑相同,我传递一个 ArrayList 模板来运行?

问题是你声明了一个函数模板,其中模板模板参数container_type接受任意数量的类型,但你传递的是类型和类模板(std::vector)。为了使它接受std::vectorstd::set您需要使用模板模板参数作为container_type模板参数的第二个参数,即将模板更改为

template <template <typename, template <typename...> typename> typename container_type>
void test_int(std::string container_name) {
    container_type<int, std::vector> container1;
    container_type<int, std::set> container2;
    container_type<int, std::list> container3
}

正如你在这里看到的,现在编译得很好。

最新更新