是什么最先进的关于函数检查值是否已设置?
例如,下面的迭代器解析单元格。
某些单元格包含值,其他单元格为空。
最方便的方法是什么?
struct iterator
{ //usage:
bool isset() const // if (it.isset())
bool isSet() const // if (it.isSet())
bool empty() const // if (it.empty())
bool is_set() const // if (it.is_set())
bool is_valid() const // if (it.is_valid())
operator void*() const; // if (it)
explicit operator bool() const; // if ((bool)it) or if(it) //thanks @stijn
operator bool() const; // if (it) //why not implicit conversion?
bool operator!() const; // if (!!it)
//throwing exception as pointed out by @MatthieuM
Type get() { if (isSet()) return value_; else throw; }
//usage:
// try { // if (it.isSet()) {
// Type x = it.get(); // Type x = it.get();
// } // }
// catch (...) { // else {
// //empty // //empty
// } // }
//please feel free to propose something different
...
};
反思:
- 我的老板不明白
isset()
=> 重命名为isSet()
-
empty()
更多的是关于容器收集,而不仅仅是一个单元格:(
-
operator void*
似乎是合乎逻辑的方式,但是在 C++11 流中已弃用 http://en.cppreference.com/w/cpp/io/basic_ios/operator_bool
-
explicit operator
is 尚未支持 https://stackoverflow.com/questions/11365129/explicit-operator-bool-error(我的代码必须兼容旧的编译器)
我在读:
-
http://en.wikibooks.org/wiki/More_C%2B%2B_Idioms/Safe_bool http://en.wikibooks.org/wiki/More_C%2B%2B_Idioms/Safe_bool
- ( http://www.artima.com/cppsource/safebool.html http://www.artima.com/cppsource/safebool.html )
- C++11 中的 safe-bool 习惯用法是否已过时? https://stackoverflow.com/questions/6242768/is-the-safe-bool-idiom-obsolete-in-c11
- 安全 bool 习惯用法和显式运算符 bool 之间的不兼容性 https://stackoverflow.com/questions/9383282/incompatibilities-between-safe-bool-idiom-and-explicit-operator-bool
- boost 中的安全 bool 习语? https://stackoverflow.com/questions/11781584/safe-bool-idiom-in-boost
- 增强源代码...
void*
有问题,因为它是一个有效的转换序列,但在某些情况下并非预期的。许多人在 C++03 中使用有时称为“安全布尔习语 http://www.artima.com/cppsource/safebool.html“其中您有一个包含私有类型的本地成员函数指针类型,因此没有人可以在您的类之外拥有它的实例。但是您可以返回它并至少检查 true/false。
当你使用C++11时,那么explicit operator bool
这是可行的方法,因为它主要是针对这些情况而发明的。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)