raw_rice
raw_rice

Reputation: 1

how can you make a function that accepts both float and double in c++

I dont know if its even possible but i want to make this function that calculates mean of vector accept both float and double. is there any way to make it? thanks.

#include <numeric>
#include <stdint.h>
#include <vector>

int mean(std::vector<float> var)
{
    int number = var.size();
    int varAcc = std::accumulate(var.begin(), var.end(), 0);
    return varAcc / number;
}```

Upvotes: 0

Views: 1209

Answers (1)

foragerDev
foragerDev

Reputation: 1409

You can use templates to make it work with all the types.

template<typename T>
T mean(const std::vector<T>& var)
{
    int number = var.size();
    T varAcc = std::accumulate(var.begin(), var.end(), T{});
    return varAcc / number;
}

This is how you write less code and make things work on the types that supports the operations used in the function templates and template classes.

Upvotes: 1

Related Questions