Is there any method to use 'delete' more efficiently instead of deleting one-by-one?

Viewed 60

I'm trying to make function that gets only int parameters. So when other types(double, char, bool) are included I used delete to exclude that like this code:

#include <iostream>

using namespace std;

int add_int(int x, int y){
    return x + y;
}

int add_int(double, double) = delete;
int add_int(int, double) = delete;
int add_int(double, int) = delete;
int add_int(bool, int) = delete; // need much more code.. very inefficient

int main(void){
    cout << add_int(1, true) << endl; // error should happen
}

But I think this is so inefficient. Is there any method like 'only int possible' or 'exclude double, char, bool(I mean input only one parameter)'?

1 Answers

Yes, you can use a function template that deletes everything.

template<class X, class Y>
int add_int(X, Y) = delete;

Now, when the compiler is resolving a function call, it will select the template unless there is a function overload where implicit type conversion is not required. An overload that requires no conversions will be selected in preference to a template function.

More information here: Overload resolution

If you like, you can also make your implementations part of this template by adding specializations:

template<>
int add_int(int x, int y)
{
    return x + y;
}
Related