How can you make sure a C++ function can be called as e.g. void foo(int, int) but not as any other type like void foo(long, long)?
Asked
Active
Viewed 210 times
8
-
2Are you trying to solve a specific problem, or is this academic? – Stephen Newell Feb 09 '21 at 18:02
1 Answers
17
Add a deleted template overload:
template <typename A, typename B> void foo(A, B) = delete;
void foo(int x, int y) {...}
It will be a better match (causing a error) for any argument types except int, int
.

HolyBlackCat
- 78,603
- 9
- 131
- 207
-
3`foo(0LL, {});` calls the `int` version with a `long long` and an `int`. – Aykhan Hagverdili Feb 09 '21 at 18:14
-
-
2@user975989 do you then have to do this for all permutations of 3 or more arguments? – Aykhan Hagverdili Feb 09 '21 at 18:19
-
@AyxanHaqverdili Hmm good point, maybe you can make `foo` a template and specialize it for `
`? Seems kludgy, probably better to make a wrapper type that can only be constructed from `int` (in a similar way to this). – user975989 Feb 09 '21 at 18:23