2

具有模板功能 -

template <class B>
B getValue (B& map) {
    // implementation ...       
}

对此函数 a 传递 a map,例如 -

map<string,double> doubleMap;
getValue (doubleMap);

因此,例如在这种情况下,如果我想将函数的返回值double设置为根据doubleMap我应该提取this的value 类型map ,如果我想声明一个双精度(或根据传递的映射的任何其他类型)我必须有这个..

我怎么才能得到它 ?

4

3 回答 3

8

std::map defines the member types key_type and mapped_type.

What you want is B::mapped_type, which will be double in your case.

于 2012-12-06T09:34:50.857 回答
2

您可以创建一个接收容器并使用 typedef 导出其类型参数的模板:(一般模板参数类型检索的示例)

template <typename>
class GetTemplateArgs {};

template <typename ARG1, typename ARG2>
class GetTemplateArgs<std::map<ARG1,ARG2>>
{
  public:
    typedef ARG1 KEY;
    typedef ARG2 DATA;
};

template <class B>
typename GetTemplateArgs<B>::DATA getValue (B& map) {
    // implementation ...       
}

当然,您可以将其更具体地用于地图,因此它只会接收地图作为参数。

于 2012-12-06T09:37:46.800 回答
0

以防万一它有帮助,这是我如何做的一个例子:

    template<typename MapType>
    static auto GetValueOrDefault(const MapType& map, const std::string& key, const typename MapType::mapped_type& defaultVal)
    {
        // Try to find the key
        auto iter = map.find(key);
        
        // If we didn't find it then return the default value
        if (iter == map.end())
            return defaultVal;

        // Return the value
        return iter->second;
    }

这类似于 arnoo 的回答,但我必须做的另一件事是在函数参数列表中的“MapType::mapped_type”之前添加关键字“typename”。

于 2021-12-08T11:02:05.223 回答