4 ms·
No it doesn't, which is one of the major advantages it has over the C version; you have to do an explicit cast when the args are different types (almost always
by smitherfield 9y ago
No it doesn't, which is one of the major advantages it has over the C version; you have to do an explicit cast when the args are different types (almost always a potential source of subtle bugs).
Or what edflsafoiewq said: https://news.ycombinator.com/item?id=16721559 https://news.ycombinator.com/item?id=16721559
It is however trivial to write a version that works with distinct types, if that were really what you want.
template<class L, class R>
constexpr std::common_type_t<L, R> max(L l, R r) {return l < r ? r : l;}
- Too 9y agoAssuming the single template argument version. If T has an implicit constructor taking type R as argument, wouldn't the second argument into max of type R be implicitly converted to T before getting passed to the max function? So there is no need for a special version taking both L and R? This is a property of c++ implicit constructor rules, it is not unique to this function. In most cases this is something you want to avoid but for integer promotion it can some times be useful.
- smitherfield 9y agoNope, template type deduction never implicitly converts: https://godbolt.org/g/stZBK1 https://godbolt.org/g/stZBK1
- Too 9y agoOh, "conflicting types for parameter 'T' ('T2' vs. 'T1')". I'm surprised but it's a nice surprise. Finally something in c++ where safety is valued more than implicit dangerous magic.
- bstamour 9y agoC++'s type system has always been stricter than C's. Even the following, totally valid C program, is ill-formed C++ int* x = malloc(5 * sizeof (int)); because in C++ you cannot implicitly cast a void pointer.