如何从模板类中的方法返回NULL [英] How to return NULL from a method in a Template Class

查看:90
本文介绍了如何从模板类中的方法返回NULL的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个如下所示的方法:

I have a method which looks like this:

template <typename T>
T Test<T>::FindItem(T item)
{
    if(found)
        //return original value, no problem here
    else
        //I want to return NULL here, like:
        return NULL; 
}

这在运行时在某些情况下会失败,因为某些值不能在C ++中转换为NULL,例如, std :: string 。我应该在这里采用什么方法?

This fails in certain cases at runtime because some of the values can't be converted to NULL in C++ e.g., std::string. What approach should I follow here?

推荐答案

如果你想返回值,不想混乱返回指针和new / delete,你可以这样做:

If you want to return by value and don't want to mess with returning pointers and new/delete, you can just do like this:

template <typename T>
boost::optional<T> Test<T>::FindItem(T item)
{
    if(found)
        //return original value
    else
        return boost::none; 
}

并以此方式使用:

Test<int> var;
boost::optional<int> V = var.FindItem(5)

if (V)
{
    // found
    int val = *V;
}
else
{
    // not found
}

这篇关于如何从模板类中的方法返回NULL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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