简体   繁体   中英

How to implicitly cast all arguments of a template function to the highest resolution type?

In a project I'm working on I have a templated function similar to this where all of the arguments should be of type T

#include <iostream>

template<typename T> bool aWithinBOfC(T a, T b, T c)
{
    return std::abs(a - c) < b;
}

the issue I'm having is it won't compile if all of the arguments are not of the same type but it seems reasonable that it should implicitly cast similar types to the one with the highest resolution before evaluation. Is there any way to get a call like this to be valid?

int main()
{
    double a{1.2};
    double b{1.4};
    float c{0.1f};

    std::cout << aWithinBOfC(a, b, c) << std::endl;
}

Something along these lines, perhaps:

template<typename T>
bool aWithinBOfCImpl(T a, T b, T c) {
  /* actual implemenattion */
}

template <typename ... Args>
auto aWithinBOfC(Args... args) {
  return aWithinBOfCImpl<std::common_type_t<Args...>>(args...);
}

Demo

You don't need implicit conversions at the call site. The compiler will implicitly convert the types to the largest one in the expression in the return statement.

template <class T, class U, class V>
bool aWithinBOfC(T a, U b, V c) {
    return std::abs(a - c) < b;
}

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