2
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.

Mat
  • 202,337
  • 40
  • 393
  • 406
k.b
  • 157
  • 1
  • 2
  • 13
  • Related: [auto parameter type in functions](https://stackoverflow.com/questions/31648458/auto-parameter-type-in-functions) – Remy Lebeau Jul 07 '19 at 19:11

2 Answers2

7

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;
}
SolidMercury
  • 973
  • 6
  • 15
6

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;
};
David Ledger
  • 2,033
  • 1
  • 12
  • 27