Variable return type

3

I want to do functions with type variant input, like this:

int count(vector<auto> base, auto val)
{
    int sum= 0;

    for (auto it : base)
    {
        if (it == val)
        {
            sum++;
        }
    }

    return sum;
}

or this:

string str(auto a)
{
    stringstream x;
    x << a;
    return x.str();
}

But of course, it did not work. I received the following error:

error: invalid use of 'auto'

How can I do this?

    
asked by anonymous 24.06.2017 / 21:19

1 answer

3

I think you want to use a function template , like this:

#include <iostream>
#include <vector>
using namespace std;

template<typename T> 
vector<T> filter(vector<T> base, T val) {
    vector<T> temp;
    for (auto it : base) if (it == val) temp.push_back(it);
    return temp;
}

int main() {
    vector<int> v = {7, 5, 16, 8, 5, 12, 1};
    for (auto it : filter(v, 5)) cout << it << endl;
}

See running on ideone . And no Coding Ground . Also I put it in GitHub for future reference .

Note that there are generic algorithms ready in C ++ to do this, for example copy_if() or the remove_if() . Not the same thing, but they may be more useful.

    
24.06.2017 / 23:18