How do I avoid implicit casting on non-constructing functions?
I have a function that takes an integer as a parameter,
but that function will also take characters, b
Here's a general solution that causes an error at compile time if function is called with anything but an int
template
struct is_int { static const bool value = false; };
template <>
struct is_int { static const bool value = true; };
template
void function(T i) {
static_assert(is_int::value, "argument is not int");
return;
}
int main() {
int i = 5;
char c = 'a';
function(i);
//function(c);
return 0;
}
It works by allowing any type for the argument to function but using is_int as a type-level predicate. The generic implementation of is_int has a false value but the explicit specialization for the int type has value true so that the static assert guarantees that the argument has exactly type int otherwise there is a compile error.