是否可以使用 std::p air 作为关联容器(如 std::map)的(唯一)模板参数

Is it possible to use a std::pair as (sole) template argument for an associative container like std::map?

本文关键字:std map 参数 唯一 可以使 air 是否 关联      更新时间:2023-10-16

标题对于我想知道的内容可能不够描述:
请考虑以下代码:

typedef std::pair<std::string, int> myPair;
typedef std::map<std::string, int> myMap;

如您所见,两个 typedef 都使用相同的模板参数。现在,我想确保两个 typedef 始终使用相同的模板参数。实现此目的的一种迂回方法可能是:

typedef arg1 std::string;
typedef arg2 int;
typedef std::pair< arg1, arg2 > myPair;
typedef std::map< arg1, arg2 > myMap;

现在,我想知道,如果有更好的方法,类似于:

typedef std::pair<std::string, int> myPair;
typedef std::map< myPair > myMap;

提前感谢您的任何指向正确方向的指示!

#include <map>
#include <utility>
template <typename T>
struct make_map;
template <typename K, typename V>
struct make_map<std::pair<K,V> >
{
    typedef std::map<K,V> type;
};

测试:

#include <string>
int main()
{
    typedef std::string arg1;
    typedef int arg2;
    typedef std::pair<arg1, arg2> myPair;
    typedef make_map<myPair>::type myMap;
    myMap m;
    m["foo"] = 1;
}

演示