gpt4 book ai didi

c++ - 如何从模板类中的方法返回 NULL

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:48:52 25 4
gpt4 key购买 nike

我有一个看起来像这样的方法:

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。我应该遵循什么方法?

最佳答案

如果你想按值返回并且不想弄乱返回指针和新建/删除,你可以这样做:

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
}

关于c++ - 如何从模板类中的方法返回 NULL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1392869/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com