1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54
|
In addition to explicit constructors, bf(C++) supports
hi(explicit: conversion operator)hi(conversion operator: explicit)
em(explicit conversion operators).
For example, a class might define tt(operator bool() const) returning tt(true)
if an object of that class is in a usable state and tt(false) if not.
Since the type tt(bool) is an arithmetic type this could result in unexpected
or unintended behavior. Consider:
verb( void process(bool value);
class StreamHandler
{
public:
operator bool() const; // true: object is fit for use
...
};
int fun(StreamHandler &sh)
{
int sx;
if (sh) // intended use of operator bool()
... use sh as usual; also use `sx'
process(sh); // typo: `sx' was intended
})
In this example tt(process) unintentionally receives the value returned by
tt(operator bool) using the implicit conversion from tt(bool) to tt(int).
When defining tt(explicit) conversion operators implicit conversions like the
one shown in the example are prevented. Such conversion operators can only be
used in situations where the converted type is explicitly required (as in the
condition clauses of tt(if) or tt(while) statements), or is explicitly
requested using a tt(static_cast). To declare an explicit bool conversion
operator in class tt(StreamHandler)'s interface replace the above declaration
by:
verb( explicit operator bool() const;)
Since the C++14 standard tt(istreams) define an
tt(explicit operator bool() const). As a consequence:
verb( while (cin.get(ch)) // compiles OK
;
bool fun1()
{
return cin; // 'bool = istream' won't compile as
} // istream defines 'explicit operator bool'
bool fun1()
{
return static_cast<bool>(cin); // compiles OK
})
|