gpt4 book ai didi

c++ - isSet() 或 operator void*() 或 explicit operator bool() 或其他?

转载 作者:可可西里 更新时间:2023-11-01 17:41:56 26 4
gpt4 key购买 nike

关于检查值是否已设置的函数的最新技术水平是什么?

例如,下面的迭代器解析单元格。一些单元格包含一个值,其他单元格为空。

哪种方式最方便?

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
...
};

反射(reflection):

  1. 我老板不懂 isset() => 重命名为 isSet()
  2. empty() 更多的是关于容器集合,而不仅仅是一个单元格:(
  3. operator void* 似乎是合乎逻辑的方式,但 deprecated in C++11 streams
  4. 显式运算符not yet supported (我的代码必须与旧编译器兼容)

我正在阅读:

最佳答案

void* 有问题,因为它是一个有效的转换序列,但在某些情况下不是预期的。许多人在 C++03 中使用有时称为“safe bool idiom”的地方,您有一个包含私有(private)类型的本地成员函数指针类型,因此没有人可以在您的类之外拥有它的实例。但是,您可以返回它并至少检查真/假。

当您使用 C++11 时,explicit operator bool 是正确的选择,因为它主要是为这些情况而发明的。

关于c++ - isSet() 或 operator void*() 或 explicit operator bool() 或其他?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13193766/

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