I have a function:
void foo(int n) {
std::cout << "foo(int)\n";
}
which can be called using different arguments, it can be char, double, float etc.:
foo(123); // 1
foo('c'); // 2
foo(0.2); // 3
foo(0.2f); // 4
// ...
... but I would like to allow only int
arguments (literal or variable), so that 2,3,4,... above would be illegal. My current solution is to delete those overloads with:
void foo(char) = delete;
void foo(float) = delete;
void foo(double) = delete;
but this list of overloads can be really long, and always someone can write a class which will implicitly convert to int
what will allow to use my int
only function in wrong way, so I found that writing (instead of long explicit list):
template<typename T>
void foo(T) = delete;
works as expected.
Is there any downside to using template as above? or maybe there are some better ways to aprach this problem?
You can use static_assert
with std::is_same
:
template<typename T>
void foo(T i) {
static_assert(std::is_same<T, int>::value, "Not int");
std::cout << "foo(int)\n";
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With