C++11 shows the advantages of type conversion

  • 2020-11-18 06:22:48
  • OfStack

1. Problem of implicit type conversion

Implicit casting is a love-hate feature of C++1. It's easy to use, but it can make your code less readable and even cause 10-point bugs.


#include <iostream>
using namespace std;

class MyInt
{
public:
	// Single argument constructor 
	explicit MyInt(int value) :_value(value)
	{}

	// Type conversion operator 
	operator bool() const noexcept
	{
		return _value != 0;
	}

	// Add operator overload 
	MyInt& operator+(const MyInt& right)
	{
		_value += right.getValue();
		return *this;
	}

	int getValue() const
	{
		return _value;
	}
private:
	int _value;
};

int main()
{
	MyInt myInt1(1);
	MyInt myInt2(2);
	cout << "myInt1+myInt2=" << myInt1 + myInt2 << endl;
	return 0;
} 

Program compilation and operation output:

[

myInt1+myInt2=1

]

Although the program runs without any problems, the result of adding two MyInt objects is not the expected number 3, but 1. The reason for this subtle error is that when the two MyInt objects are added, the resulting object myInt1 is implicitly converted to bool type, resulting in an output value of 1. As the project code gets larger, the hidden errors caused by implicit casting get deeper and harder to detect.

2. Display type conversion

To prevent implicit casting, which can easily lead to subtle errors, C++11 introduced the ability of the explicit keyword to act on custom cast operators, prohibiting implicit casting. Its usage is similar to that of explicit acting on single-parameter constructors to avoid implicit type conversions caused by the implicit invocation of single-parameter constructors.


// Type conversion operator 
explicit operator bool() const noexcept
{
	return _value != 0;
}

cout << "myInt1+myInt2=" << myInt1 + myInt2 << endl;		// Compile error 

When the explicit keyword is used to modify the bool typedef operator, implicit typedef will be blocked, resulting in the above compilation error, exposing potential hidden errors to the compilation phase, allowing errors to be discovered and resolved in advance.

Note that there is one exception to explicit type conversion. If the expression is used as a condition and only the conversion to bool is limited, then the explicit operator bool() can also be implicitly done. "Used as a condition" indicates the following statement now:

(1) Conditional parts of if, while and do statements;
(2) Conditional expression of for statement header;
(3) Logical non-operator (!) , logic or operator (||), logic and operator ( & & );
(4) Conditional operator (x ? y: z).

Since the conversion to bool1 is used as a condition, operator bool()1 is modified with explicit.

These are the advantages of C++11 display type conversion in detail, more information about C++11 display type conversion please pay attention to other related articles on this site!


Related articles: