Reputation: 165
bool isEven(int val) {
return val % 2 == 0;
}
bool isOdd(int val) {
return val % 2 != 0;
}
template<class Iterator>
int count_function(Iterator start, Iterator end, auto criteria) {
int count = 0;
for (; start != end; ++start) {
if (criteria(*start)) {
count++;
}
}
return count;
}
Above is my code, auto before criteria is giving error "auto is now allowed here". I want to supply isEven /isOdd criteria to this function.
Why is that?
I have tried int, bool - that return some more problem.
Upvotes: 2
Views: 8684
Reputation: 2101
Auto isn't allowed in normal function arguments. Its only allowed in lambda arguments. C++20 is going to add this functionality :)
Also look at "Abbreviated function template", here:
https://en.cppreference.com/w/cpp/language/function_template#Abbreviated_function_template
For now, you might get away with declaring your function with a lambda:
auto count_function = [](auto start, auto end, auto criteria)
{
int count = 0;
for (; start != end; ++start) {
if (criteria(*start)) {
count++;
}
}
return count;
};
Upvotes: 7
Reputation: 1021
The keyword auto
is not allowed in function parameter. You need to use template if you want to use different datatypes.
template<class Iterator, class T>
int count_function(Iterator start, Iterator end, T criteria) {
int count = 0;
for (; start != end; ++start) {
if (criteria(*start)) {
count++;
}
}
return count;
}
Upvotes: 7