当使用Tempate作为参数时,功能模板专业化

The function template specialization when using tempates as argument

本文关键字:功能 专业化 参数 Tempate      更新时间:2023-10-16

我想编写一个函数模板来处理向量,列表,sets,...并想编写专业功能以分别处理地图,当我编写以下代码并报告错误时。

有人可以帮助我如何修改它吗?

#include <iostream>
#include <string>
#include <map>
#include <unordered_map>
using namespace std;
// test() for the vectors, lists, sets, ...
template <template <typename...> class T>
void test()
{
    T<string, int> x;
    //...
}
// specialize test() for map
template <>
void test <map<> class T>()
{
    T<string, int> x;
    //...
}

int main()
{
    test<map>();
    test<unordered_map>();
}

模板专业应为:

template <>
void test <std::map>()
{
    std::map<string, int> x;
}

我将模板参数从map<> class T更改为std::map无效的语法。我将T<string, int>更改为std::map<string, int>,因为该名称T在专业中不存在。

以下是有效的完整代码:

#include <iostream>
#include <string>
#include <map>
#include <unordered_map>
using namespace std;
template <template <typename...> class T, typename TN>
void test()
{
    cout << "---------- test case 1" << endl;
    T<TN, int> x;
}
template <template <typename...> class T>
void test()
{
    cout << "---------- test case 2" << endl;
    T<string, int> x;
}
template <> 
void test < map,string >()
{
    cout << "---------- test case 3" << endl;
    map<string, int> x;
}
template <> 
void test < map >()
{
    cout << "---------- test case 4" << endl;
    map<string, int> x;
}
int main()
{
    test<unordered_map,string>(); // trigging test case 1
    test<unordered_map>();        // trigging test case 2
    test<map,string>();           // trigging test case 3
    test<map>();                  // trigging test case 4
}