为什么关键字`explicit`不适用于函数参数?

时间:2014-03-02 04:48:22

标签: c++ c++11 type-conversion standards overloading

在某些情况下,可能不需要隐式类型转换。

例如:

#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);
}

如果C ++标准支持关键字explicit可用于限定函数参数,则代码可能会更改如下:

#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!
}

为什么C ++标准不支持这样一个方便的功能?

1 个答案:

答案 0 :(得分:4)

#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!
}