模板模板参数:没有找到匹配的调用

template template arguments: no matching call found

本文关键字:调用 参数      更新时间:2023-10-16
#include <vector>
using std::vector;
template<template<typename> class x>
void test() {
    x<int> a;
    a.push_back(1);
}
int main() {
    test<vector>();
    return 0;
}

由于某种原因,我没有得到匹配调用错误,尽管我的期望。为什么会发生这种情况?

std::vector不接受一个参数,而是接受两个参数(有Allocator),因此它不能与只接受一个参数的模板匹配。您需要更改为:

template <template <typename, typename> class x>
// or:
template <template <typename... > class x>

您还需要更改函数的返回类型,因为x<int>不太可能是void

请注意,如果您使用具有两个typename的版本,则需要在返回语句中指定每个参数(例如x<int, std::allocator<int>>),这就是为什么您应该选择可变版本(typename...)。

std::vector模板如下:

template<
    class T,
    class Allocator = std::allocator<T>
> class vector;
所以你有typename T和allocator,所以正确的代码应该是:
template<template<typename,typename> class x>
void test() {
    x<int, std::allocator<int>>();
}