在某些情况下,可能不希望进行隐式类型转换。
例如:
如果C++标准支持关键字explicit可以用于限定函数参数,代码可更改如下:
为什么C++标准不支持这样一个方便的功能?
例如:
#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++标准不支持这样一个方便的功能?
const char*
比std::string
更适合于bool
。前者是一个简单的构造,而后者则不是。所以你试图解决的问题是什么? - WhozCraigconst char*
隐式转换为bool
,该怎么办?换句话说,如果我想要禁用传递参数时的隐式类型转换,该怎么做? - xmllmxstd::string
?这就是关键吗? - WhozCraigf
函数做什么使得它可以接受bool
或者string
参数,并且可以用相同的逻辑进行处理呢? - Jerry Coffin