部分模板模板向量特化

4

我有一个通用函数,可以处理不同的容器。

template<template<class, class> class C, class T, class A>
void handle(C<T, A> const& c)
{
    cout << "General handling\n";
}

如果我传给它一个自定义容器,我希望它有不同的反应。为了简单起见,我首先尝试通过为向量部分特化此函数来以不同方式处理向量。
以下是我认为它应该看起来的样子。

template<class T, class A>
void handle<std::vector>(std::vector<T, A> const& c)
{
    cout << "vector handling\n";
}

然而gcc报错如下:

无法执行程序 编译器返回: 1 编译器stderr :16:36: 错误: 在主模板的声明中使用了句柄类std::vector>的模板ID 16 | (std::vector const& c) |

是否可以通过部分模板特化来解决?

2个回答

8

函数模板不能进行部分特化;这只适用于类模板和变量模板(自C++14起)。您可以使用函数模板重载来替代。

例如:

template<template<class, class> class C, class T, class A>
void handle(C<T, A> const& c)
{
    cout << "General handling\n";
}

template<class T, class A>
void handle(std::vector<T, A> const& c)
{
    cout << "vector handling\n";
}

2
你也可以使用函数对象。通过它们,你可以部分特化你想要的内容。
#include<iostream>
#include<vector>
#include <list>
template<template<class, class> class C, class T, class A>
struct handle {
    void operator()(C<T, A> const &c) {
        std::cout << "General handling\n";
    }
};

template<class T, class A>
struct handle<std::vector, T, A>{
    void operator()(std::vector<T, A> const& c)
    {
        std::cout << "vector handling\n";
    }
};
//To test
int main(){
    std::list<int, std::allocator<int>> ls(10,0);
    handle<std::list, int, std::allocator<int>>{} (ls);

    std::vector<int, std::allocator<int>> vec(10,0);
    handle<std::vector, int, std::allocator<int>>{} (vec);

}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接