I have a function
void foo(int *bar)
{}
Visual Studio 2012 will now happily and without warnings compile if I call foo like this:
int main()
{
foo(false);
return 0;
}
If I however change foo(false) to foo(true) than I get an error:
1>main.cpp(132): error C2664: 'foo' : cannot convert parameter 1 from 'bool' to 'int *'
1> Conversion from integral type to pointer type requires reinterpret_cast, C-style cast or function-style cast
Any idea how I can make sure that I get an error when passing false, too? My only idea is to add a second private function "void foo(bool bar)". Then I indeed get the desired error stating that foo(bool bar) is private. But this only works when foo is called from outside the class and it clutters my interface.
In C++11, you may write:
As vs2012 doesn't support
= delete
,You may try this hack using SFINAE:
With the old C++98 way 'private without implementation':
First, as to why it accepts
false
but nottrue
: The literal false will be interpreted as the integral0
and a literal0
will convert to a null pointer of any type.true
on the other hand cannot be converted to a pointer type as it converts to an integral1
.As to how to solve your problem: Your approach with an extra
bool
overload will work fine for both public and non-public callers as long as you don't implement the private overload. In that case public callers will get a compile error and member callers will get a linker error.However, you may wish to consider additional things as well.
Does your function need to accept null pointers? If not, change it to accept by reference instead and the problem just goes away.
If your function really does need to accept null pointers then I would suggest in this case to just trust your users to call it correctly instead of cluttering your interface trying to prevent every possible misuse.
You can wait for C++17, when Concepts can be used anywhere
auto
is in C++11, and write your signature as:... which actually looks pretty bad, but they may clean up the syntax by then.