Search code examples
c++functionoverloading

Do I have to overload functions for every different parameter?


I want to create a function to simplify a list/vector. I can do it in python:

i = [1, 2, 3, 4, 5]
f = [1.1, 2.2, 3.3, 4.4, 5.5]
s = ["one", "two", "three", "four", "five"]
def simplify(lst):
    if len(lst) == 0:
        return 0
    tmp = lst[0]
    for x in range(1, len(lst)):
        tmp += lst[x]
    print(tmp)
    return tmp
simplify(i)
simplify(f)
simplify(s)

but for c++ I would have to write the same function for many variable types (long long, double, int, string, char). My question is, can I do in c++ like I did in python? (creating a single function for multiple types)


Solution

  • My question is, can I do in c++ like I did in python? (creating a single function for multiple types)

    Almost. A C++ function template is not a function, but using one can look indistinguishable from it.

    You will also struggle with your choice of -1 as the result if the sequence is empty, as -1 is not a string.

    template <typename Range>
    std::ranges::range_value_t<Range> simplify(Range && range) {
        auto it = std::ranges::begin(range);
        if (it == std::ranges::end(range)) return -1; // this will fail for strings
    
        auto result = *it++;
        for (; it != std::ranges::end(range); ++it) {
            result += *it;
        }
        std::cout << result; // I assume this is for testing the function?
        return result;
    }
    

    If you make a different choice about what to do with an empty input, there is a function very similar to yours in the standard library:

    template <typename Range>
    std::ranges::range_value_t<Range> simplify(Range && range) {
        std::ranges::range_value_t<Range> zero {}; // 0 for numbers, empty string for strings, etc.
        return std::accumulate(std::ranges::begin(range), std::ranges::end(range), zero); 
    }
    
    int main() {
        std::vector<int> i {1, 2, 3, 4, 5};
        std::vector<double> f {1.1, 2.2, 3.3, 4.4, 5.5};
        std::vector<std::string> s {"one", "two", "three", "four", "five"};
        std::cout << simplify(i);
        std::cout << simplify(f);
        std::cout << simplify(s);
    }
    

    See it on coliru