C++

conversion-operator

Posted by DEVIN on Mon, Aug 14, 2023

参考文档

user-defined conversion function - cppreference.com
The Safe Bool Idiom - 知乎

一般形式为operator type() const, 比如:

1operator int() const;
2operator bool() const;
3operator AA() const;

自定义类型转换

 1struct To
 2{
 3    To() = default;
 4    To(const struct From&) {} // converting constructor
 5};
 6
 7struct From
 8{
 9    operator To() const {return To();} // conversion function
10};
11
12int main()
13{
14    From f;
15    To t1(f);  // direct-initialization: calls the constructor
16    // Note: if converting constructor is not available, implicit copy constructor
17    // will be selected, and conversion function will be called to prepare its argument
18
19//  To t2 = f; // copy-initialization: ambiguous
20    // Note: if conversion function is from a non-const type, e.g.
21    // From::operator To();, it will be selected instead of the ctor in this case
22
23    To t3 = static_cast<To>(f); // direct-initialization: calls the constructor
24    const To& r = f;            // reference-initialization: ambiguous
25}

为什么operator bool()需要用explicit修饰?

c++ - Why does declaring an operator bool() const member overload the [] operator? - Stack Overflow

The operator is coming from the built-in subscript operator which treats expressions A[B] as *(A + B).
This results in the evaluation of *(1 + "wut") => 'u', which then causes the if condition to pass, as 'u' is a non-zero value.
Declare your member as explicit operator bool() to prevent your type from being implicitly converted to other integral types.

 1#include <iostream>
 2using namespace std;
 3
 4struct Test {
 5    operator bool() const {
 6        return true;
 7    }
 8};
 9
10int main(int argc, char** argv) {
11    Test test;
12
13    if (test)
14        cout << "Object test is true\n";
15
16    if (test["wut"])
17        std::cout << "Success (test[\"wut\"])\n";
18}
19
20// Output:
21// Object test is true
22// Success (test["wut"])

一个operator bool()的坑

c++ - Why is my “explicit operator bool()” not called? - Stack Overflow