使用模板将类型发送到函数 [英] Send type into function using templates

查看:62
本文介绍了使用模板将类型发送到函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我具有此功能,用于在地图中查找键并返回正确的值,其类型为:

I have this function for finding key in map and return the right value with type:

template< typename T >
T Foo::findInMap(std::string key) {
    std::map<std::string, std::any>::iterator it = options.find(key);
    if (it != options.end())
    {
        return std::any_cast<T>(it->second);
    }
    return nullptr;
}

地图如下:

std::map<std::string, std::any> options;

如何调用和修改函数以充分利用C ++ 17?

How can I call and modify the function to get the best out of C++17?

推荐答案

并非总是可以返回 nullptr .返回可选值的现代C ++方法是使用 std :: optional .您可以使用 auto 代替长迭代器类型名称.这是您可以做到的一种方法:

Returning a nullptr is not always possible. Modern C++ way of returning optional values is to use std::optional. You can use auto instead of the long iterator type name. Here's one way you can do it:

template< typename T >
std::optional<T> findInMap(std::string key) {
    auto const it = options.find(key);
    if (it != options.end())
        return std::optional<T>{ std::any_cast<T>(it->second) };
    return std::nullopt;
}

这篇关于使用模板将类型发送到函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆