More C++ Idioms/Implicit conversions
Appearance
Implicit conversions
[edit | edit source]Intent
[edit | edit source]Implicit conversions are performed whenever an expression of some type T1 is used in context that does not accept that type, but accepts some other type T2.
Also Known As
[edit | edit source]Motivation
[edit | edit source]In some contexts a variable can be used which is not exactly the type required by the function. In particular:
- when the expression is used as the argument when calling a function that is declared with T2 as parameter;
- when the expression is used as an operand with an operator that expects T2;
- when initializing a new object of type T2, including return statement in a function returning T2;
- when the expression is used in a switch statement (T2 is integral type);
- when the expression is used in an if statement or a loop (T2 is bool).
The program is well-formed (compiles) only if there exists one unambiguous implicit conversion sequence from T1 to T2.
More info on: C++ Reference en.cppreference.com implicit_conversion
Solution and Sample Code
[edit | edit source]Conversion of pointer to boolean:
int a = 42;
int* ptr = &a;
if (ptr) // checks if ptr is not null_ptr
...
Conversion of std::string to some other type:
#include <string>
struct A {
A( const std::string & s ) {}
};
void func( const A & a ) {
}
int main() {
func( "one" ); // error - requires 2 steps to convert: const char* -> std::string -> A
func( A("two") ); // ok - converting const char* -> std::string, which is used to create A
func( std::string("three") );// ok - implicit conversion std::string -> A
}
Example comes from this Stack overflow question titled: C++ implicit conversions.
Known Uses
[edit | edit source]Everywhere, all the time, ...