【发布时间】:2013-11-29 10:29:34
【问题描述】:
这是交易:
当我有一个像这样的默认参数的函数时
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);
但是这种方法太乱了,让代码混乱。
有明确的关键字,但它只适用于构造函数。
我想要的是一种类似于显式方法的干净方法,这样当我像这样声明方法时:
(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)
有这样的方法吗?
【问题讨论】:
-
当您拥有
void foo(short a, int b, long c)并且您将其称为foo(1, 1, 1)时,您希望它做什么? “哦,那些隐式转换没问题” -
实际上这些不是转换,因为整数是模棱两可的数据。我想在调用 foo (a (int), b (some other object) ) 时阻止大部分转换;这些错别字让我很头疼。
-
1是一个int。 stackoverflow.com/a/8108658/242520 -
您遇到的问题与隐式转换无关;这是关于文字的。在隐式转换的情况下,编译器已经给出了您期望的错误,例如
bool x = false; foo(1, x);
标签: c++ casting default implicit explicit