WhiteWolf
WhiteWolf

Reputation: 25

Passing arbitrary-templated vector as function argument C++

Sorry if this is something trivial, and it also may not be of huge importance, but I'm just curious and I couldn't find an answer yet.

In C++ I'm creating functions to evaluate some stuff in a vector, the result is double, but I want the function to work for both vector and vector. The solution I go for is overload, as in this showcase simple example:

double silly_example(vector<int> &vec){
    return vec[0] + vec[1];
}
double silly_example(vector<double> &vec){
    return vec[0] + vec[1];
}

However, it is true for all functions that there is no difference in the body of the overloaded functions. As said, the result is double, the calculations use double. If a vector is passed, the int members are converted to double anyway. So is there a way to somehow avoid having to overload each of these functions and just tell the compiler that the template here doesn't matter as long as its something numeric? I wish for something like:

double wished_form(vector<auto> &vec){
    return (double) vec[0] + (double) vec[1];
}

I know the auto doesn't work like that, this is just to showcase what I mean: is there some way like this to combine the two overloaded functions into one?

Thanks and sorry if this is trivial or silly.

Upvotes: 0

Views: 69

Answers (1)

Brian Bi
Brian Bi

Reputation: 119099

It's easy:

template <class T>
double wished_form(const vector<T>& vec) {
    return (double) vec[0] + (double) vec[1];
}

If T is not convertible to double, a compile-time error will occur.

Upvotes: 4

Related Questions