4

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?

Jean-Luc Nacif Coelho
  • 1,006
  • 3
  • 14
  • 30
  • 2
    What do you expect it to do when you have `void foo(short a, int b, long c)` and you call it like `foo(1, 1, 1)` ? "Oh those implicit conversions are okay" – ta.speot.is Nov 29 '13 at 10:31
  • Actually those aren't conversions because integers are ambiguous data. I want to prevent mostly conversion when calling foo (a (int), b (some other object) ); Those typos have given me a lot of headaches. – Jean-Luc Nacif Coelho Nov 29 '13 at 10:35
  • 1
    `1` is an `int`. http://stackoverflow.com/a/8108658/242520 – ta.speot.is Nov 29 '13 at 10:40
  • The problem you're having is unrelated to implicit conversions; it's about literals. The compiler *already* gives the error you expect in the case of implicit conversions, such as `bool x = false; foo(1, x);` –  May 19 '15 at 18:53

2 Answers2

5

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]

ForEveR
  • 55,233
  • 2
  • 119
  • 133
3

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);
BЈовић
  • 62,405
  • 41
  • 173
  • 273