如何使用boost ::可选&LT; T&GT;在C ++中返回NULL? [英] How to use boost::optional<T> to return NULL in C++?
本文介绍了如何使用boost ::可选&LT; T&GT;在C ++中返回NULL?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有需要在某些情况下,返回NULL并且存在需要来测试这种函数的返回值的另一功能的功能。我知道的boost ::可选的,但我不知道如何使用语法。
I have a function that needs to return NULL in some cases and there is another function that needs to test for the return value of this function. I am aware of boost::optional but am not sure how to use the syntax.
下面将所述使用的一个简单的例子:
Below would be a simple example of said usage:
int funct1(const string& key) {
// use iterator to look for key in a map
if(iterator == map.end()) {
return NULL // need help here!
else
return it->second;
}
void funct2(string key) {
if(funct1(key) == NULL) { // <-- need help here!
// do something
} else {
// do something else
}
可有人请与语法的帮助?
Can someone please help with the syntax?
感谢。
推荐答案
它停留在 NULL
状态,直到你把它。你可以使用这个成语:
It stays in the "NULL
" state until you set it. You can use this idiom:
optional<int> funct1(const string& key) {
// use iterator to look for key in a map
optional<int> ret;
if (iterator != map.end())
{
ret = it->second;
}
return ret;
}
然后:
if (!funct1(key)) { /* no value */ }
这篇关于如何使用boost ::可选&LT; T&GT;在C ++中返回NULL?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文