Reputation: 1022
Here's the deal:
When i have a function with default arguments like this one
int foo (int a, int*b, bool c = true);
If i call it by mistake like this:
foo (1, false);
The compiler will convert false to an int pointer and call the function with b pointing to 0.
I've seen people suggest the template approach to prevent implicit type conversion:
template <class T>
int foo<int> (int a, T* b, bool c = true);
But that approach is too messy and makes the code confusing.
There is the explicit keyword but it only works for constructors.
What i would like is a clean method for doing that similarly to the explicit method so that when i declare the method like this:
(keyword that locks in the types of parameters) int foo (int a, int*b, bool c = true);
and call it like this:
foo (1, false);
the compiler would give me this:
foo (1, false);
^
ERROR: Wrong type in function call (expected int* but got bool)
Is there such a method?
Upvotes: 4
Views: 1475
Reputation: 64223
The best way is to set the warning level properly, and not ignore warnings.
For example gcc, has the -Wall
option, which handles lots of problematic cases, and will show next warning in your case (g++ 4.8.1):
garbage.cpp: In function ‘int main(int, char**)’:
garbage.cpp:13:13: warning: converting ‘false’ to pointer type for argument 2 of ‘int foo(int, int*, bool)’ [-Wconversion-null]
foo(0,false);
Upvotes: 3
Reputation: 55887
No, there is no such method. Template is good for such thing, I think. However, in gcc for example there is flag -Wconversion-null
, and for code with foo(1, false)
it will give warning
converting «false» to pointer type for argument 2 of «int foo(int, int*, bool)» [-Wconversion-null]
and in clang there is a flag -Wbool-conversion
initialization of pointer of type 'int *' to null from a constant boolean expression [-Wbool-conversion]
Upvotes: 5