简体   繁体   中英

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM