gpt4 book ai didi

C++ 如何防止编译器在调用函数时进行隐式转换?

转载 作者:太空宇宙 更新时间:2023-11-03 10:46:30 25 4
gpt4 key购买 nike

这是交易:

当我有一个带有默认参数的函数时

int foo (int a, int*b, bool c = true);

如果我这样错误地调用它:

foo (1, false);

编译器会将 false 转换为 int 指针并调用 b 指向 0 的函数。

我见过有人建议使用模板方法来防止隐式类型转换:

template <class T>
int foo<int> (int a, T* b, bool c = true);

但这种做法太过凌乱,使代码困惑。

有 explicit 关键字,但它仅适用于构造函数。

我想要的是一种类似于显式方法的干净方法,这样当我这样声明方法时:

(keyword that locks in the types of parameters) int foo (int a, int*b, bool c = true);

并这样调用它:

foo (1, false);

编译器会给我这个:

foo (1, false);
^
ERROR: Wrong type in function call (expected int* but got bool)

有这样的方法吗?

最佳答案

不,没有这样的方法。我认为模板很适合这样的事情。但是,例如在 gcc 中有标志 -Wconversion-null,对于带有 foo(1, false) 的代码,它会给出警告

converting «false» to pointer type for argument 2 of «int foo(int, int*, bool)» [-Wconversion-null]

在 clang 中有一个标志 -Wbool-conversion

initialization of pointer of type 'int *' to null from a constant boolean expression [-Wbool-conversion]

关于C++ 如何防止编译器在调用函数时进行隐式转换?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20283572/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com