Home > Software design >  How can I make a template resolve type only by first parameter?
How can I make a template resolve type only by first parameter?

Time:09-03

How can I have a function like this

template<typename TValue>
TValue GridSnap(TValue Value, TValue Grid)

That resolves template type from only the first parameter like this

GridSnap(ADouble, AFloat)  => TValue should resolve to double
GridSnap(AFloat,  ADouble) => TValue should resolve to float
GridSnap(AFloat,  AInt)    => TValue should resolve to float

basically I don't want to manually cast the second argument, it would be nice if it could just do implicit cast base on the first parameter.

CodePudding user response:

What you want to do is to have the template parameter of the second function parameter to be in a non-deduced context. You can do this using std::type_identity like

template <typename TValue>
TValue GridSnap(TValue Value, std::type_identity_t<TValue> Grid)

If you can't use C 20, then you can just write your own type_identity and type_identity_t like

template <typename T>
struct type_identity 
{
    using type = T;
};

template <typename T>
using type_identity_t = typename type_identity<T>::type;

CodePudding user response:

@NathanOliver solution worked nicely, But I also found this solution

TValue GridSnapAuto(TValue Value, decltype(Value) Grid)
  • Related