我有一个看起来像这样的方法:
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/