如何定义函数的标题以使用模板检查C ++中的映射

时间:2015-08-21 09:54:56

标签: c++ templates dictionary

我喜欢的是创建一个可以检查具有键/值对的两个映射的函数,其中键和值可以是任何类实例。

我先尝试过(编译):

template<typename T>
bool EqualsMap(int lineNumber, T_String mapText, const T& mapToCheck,     
 T_String expectedText, const T& expectedMap)
{
    ...
}

但在这种情况下,它可以接收任何类型的类(不仅仅是地图),而且转换可能会导致问题。

以下是我喜欢的内容:

template<class T1, class T2>
bool EqualsMap(int lineNumber, T_String mapText, map<T1, T2> mapToCheck,    
 T_String expectedText, map<T1, T2>expectedMap)
{
    ...
}

但是这不会编译(或者......在&lt;之前预期)

如何实现此函数的标题以接受两个同样类型的映射?

1 个答案:

答案 0 :(得分:2)

应该只是

template<class Key, class Value>
bool EqualsMap(int lineNumber, T_String mapText,
const std::map<Key, Value>& mapToCheck, T_String expectedText,
const std::map<Key, Value>& expectedMap)
{
    ...
}

当然不要忘记#include <map>。 如果你想使用任何类似地图的类,你可以使用像

这样的东西
template<template<typename, typename, typename, typename> class Map,
class Key, class Value, class Alloc, class Comp>
bool EqualsMap(int lineNumber, T_String mapText,
const Map<Key, Value, Alloc, Comp>& mapToCheck, T_String expectedText,
const Map<Key, Value, Alloc, Comp>& expectedMap)
{
    ...
}

如果你可以使用C ++ 11,它可以像

template<typename Container>
auto EqualsMap(int lineNumber, T_String mapText,
    const Container& mapToCheck, T_String expectedText,
    const Container& expectedMap) -> 
    decltype(std::declval<Container>().begin()->first, bool())

此函数仅用于容器,value_type首先具有成员(如std :: pair)。