Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does the keyword `explicit` not apply to function parameters?

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?

like image 399
xmllmx Avatar asked Dec 07 '25 02:12

xmllmx


1 Answers

#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!
}
like image 149
Cheers and hth. - Alf Avatar answered Dec 08 '25 15:12

Cheers and hth. - Alf