显式转换运算符 (C++11)
注: IBM 支持 C++11的所选功能,在批准之前称为 C++0x 。 IBM 将继续开发和实施此标准的功能部件。 语言级别的实现基于 IBM对标准的解释。 在完成 IBM对所有 C++11 功能部件的实现 (包括对新的 C++11 标准库的支持) 之前,实现可能会随着发行版而更改。 IBM 不会尝试在源代码,二进制或列表以及其他编译器接口中维护与 IBM的先前发行版实现新的 C++11 功能部件的兼容性。
您可以应用explicit函数说明符,用于定义用户定义的转换函数,以禁止应用非预期隐式转换。 此类转换函数称为显式转换运算符。
Explicit conversion operator syntax
>>-explicit--operator--conversion_type-------------------------->
>--+----------------------+--(--)--+----------+----------------->
| .------------------. | +-const----+
| V | | '-volatile-'
'---pointer_operator-+-'
>--+---------------------+-------------------------------------><
'-{--function_body--}-'
以下示例演示了通过用户定义的转换函数进行的预期和非预期隐式转换,该转换函数不符合以下条件:explicit函数说明符。
示例1
#include <iostream>
template <class T> struct S {
operator bool() const; // conversion function
};
void func(S<int>& s) {
// The compiler converts s to the bool type implicitly through
// the conversion function. This conversion might be intended.
if (s) { }
}
void bar(S<int>& p1, S<float>& p2) {
// The compiler converts both p1 and p2 to the bool type implicitly
// through the conversion function. This conversion might be unintended.
std::cout << p1+p2 << std::endl;
// The compiler converts both p1 and p2 to the bool type implicitly
// through the conversion function and compares results.
// This conversion might be unintended.
if (p1==p2) { }
}
要禁止应用非预期隐式转换,您可以通过在示例 1 中使用以下内容限定转换函数来定义显式转换运算符:explicit函数说明符:
explicit operator bool() const;
如果编译与示例 1 相同的代码,但使用显式转换运算符,那么编译器会针对以下语句发出错误消息:
// Error: The call does not match any parameter list for "operator+".
std::cout << p1+p2 << std::endl;
// Error: The call does not match any parameter list for "operator==".
if(p1==p2)
如果您打算通过显式转换运算符应用转换,那么必须像以下语句中一样显式调用显式转换运算符,然后可以获得与示例 1 相同的结果。
std::cout << bool(p1)+bool(p2) << std::endl;
if(bool(p1)==bool(p2))
在期望布尔值的上下文中,例如,&&,||,或者使用条件运算符,或者当条件表达式if对语句求值,显式bool可以隐式调用转换运算符。 因此,当您使用先前的显式转换运算符编译示例 1 时,编译器也会转换s在func函数到bool通过显式输入bool转换运算符。 示例 2 还演示了以下内容:
示例2
struct T {
explicit operator bool(); //explicit bool conversion operator
};
int main() {
T t1;
bool t2;
// The compiler converts t1 to the bool type through
// the explicit bool conversion operator implicitly.
t1 && t2;
return 0;
}