In certain cases, implicit type conversion may not be desired.
For example:
#include <string>
using namespace std;
void f(bool)
{}
void f(string)
{}
int main()
{
auto p = "hello";
f(p); // Oops!!! Call void f(bool); rather than void f(string);
}
If the C++ standard supports the keyword explicit can be used to qualify function parameters, the code may be changed as follows:
#include <string>
using namespace std;
void f(explicit bool) // Illegal in current C++11 standard!
{}
void f(string)
{}
int main()
{
auto p = "hello";
f(p); // Call void f(string);
bool b = true;
f(b); // Call void f(bool);
f(8); // Error!
}
Why does the C++ standard not support such a handy feature?
#include <string>
#include <type_traits> // std::is_same
#include <utility> // std::enable_if
using namespace std;
template< class Value >
struct Explicit_
{
Value value;
operator Value() const { return value; }
template<
class Arg,
class Enabled = typename enable_if< is_same< Arg, Value >::value, void >::type
>
Explicit_( Arg const v ): value( v ) {}
};
void f( Explicit_<bool> ) // Valid in current C++11 standard!
{}
void f( string )
{}
int main()
{
auto p = "hello";
f(p); // Call void f(string);
bool b = true;
f(b); // Call void f(bool);
f(8); // Error!
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With