With addition of change in c++11
change:Change: Specify use of explicit in existing boolean conversion operators ( https://timsong-cpp.github.io/cppwp/n4618/diff.cpp03.input.output )
can valid c++03 code break in c++11?
struct abt {
public:
abt(int a, double b){}
abt(int a){cout<<"int"<<endl;}
abt(bool b) {cout<<"bool"<<endl;}
abt(bool b,bool c) {cout<<"bool bool"<<endl;}
operator bool() const { return true; } };
int main() {
abt is("a",3);
if (is)
std::cout << "success";
if( is == true)
std::cout << "success";
return 0;
}
this valid c++03 code giving same output in c++11,output with implicit boolean conversion is also same in in c++11. Is there smthing wrong with rule?
Even if your abt
would have only an explicit converion if(is)
would be fine in C++11, because the condition of an if
is a context where explicit conversions are "implicit". From cppreference :
In the following contexts, the type bool is expected and the implicit conversion is performed if the declaration
bool t(e);
is well-formed (that is, an explicit conversion function such asexplicit T::operator bool() const;
is considered). Such expression e is said to be contextually converted to bool .
- the controlling expression of
if
,while
,for
;- ...
What changed in C++11 is this and many implicit conversions to bool of standard types changed to explicit conversions. For example std::istream::operator bool
:
operator void*() const; (1) (until C++11)
explicit operator bool() const; (2) (since C++11)
Code that was always wrong, but compiled before will now fail to compile, which is good. For example:
#include <iostream>
void foo(bool){}
int main()
{
foo(std::cout);
}
On the other hand, if you wrote code like this and the implicit conversion was intentional, then your code breaks in C++11.
TL;DR:
This is not a breaking change for if(is)
. If it was fine before it is fine now (whether is
is your custom type with an conversion to bool
or a standard type, and irrespective of wether the conversion is explicit or not). If you rely too much on implcit conversions of standard types you might encounter one or two surprises though.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.