Jea*_*lho 4 c++ casting default explicit implicit
这是交易:
当我有一个带有像这样的默认参数的函数时
int foo (int a, int*b, bool c = true);
Run Code Online (Sandbox Code Playgroud)
如果我错误地这样称呼它:
foo (1, false);
Run Code Online (Sandbox Code Playgroud)
编译器会将 false 转换为 int 指针并调用 b 指向 0 的函数。
我见过人们建议使用模板方法来防止隐式类型转换:
template <class T>
int foo<int> (int a, T* b, bool c = true);
Run Code Online (Sandbox Code Playgroud)
但这种方法太混乱并且使代码变得混乱。
有显式关键字,但它仅适用于构造函数。
我想要的是一种与显式方法类似的干净方法,这样当我声明该方法时,如下所示:
(keyword that locks in the types of parameters) int foo (int a, int*b, bool c = true);
Run Code Online (Sandbox Code Playgroud)
并这样称呼它:
foo (1, false);
Run Code Online (Sandbox Code Playgroud)
编译器会给我这个:
foo (1, false);
^
ERROR: Wrong type in function call (expected int* but got bool)
Run Code Online (Sandbox Code Playgroud)
有这样的方法吗?
不,没有这样的方法。我认为模板很适合这样的事情。然而,例如在 gcc 中有 flag -Wconversion-null
,对于带有foo(1, false)
它的代码会给出警告
\n\n\n将 \xc2\xabfalse\xc2\xbb 转换为 \xc2\xabint foo(int,\n int*, bool)\xc2\xbb 的参数 2 的指针类型 [-Wconversion-null]
\n
叮当声中有一面旗帜-Wbool-conversion
\n\n将“int *”类型的指针从常量\n布尔表达式初始化为 null [-Wbool-conversion]
\n