I am reading this question on isocpp FAQ here, this question is explaining how to write the return type for ???
template<class T, class U>
??? mul(T x, U y)
{
return x*y;
}
I understand the easy way is to write auto mul(T x, U y) -> decltype(x*y)
, however the question also gives another way, which is to replace ???
by decltype(*(T*)(0)**(U*)(0))
. But I don't fully understand what this decltype(*(T*)(0)**(U*)(0))
is really doing, it seems that it is declaring a temporary pointer T*
and initialize it to zero and then dereference the pointer, then multiplied by the same counterpart for type U
, is my understanding right?
But why using pointers? I think decltype(T(0)*U(0))
or decltype(T{0}*U{0})
should also work.
decltype(*(T*)(0)**(U*)(0))
Let's split it up:
(T*)(0) //cast a null pointer to a T*
*(T*)(0) //dereference, giving a T
(U*)(0) //cast a null pointer to a U*
*(U*)(0) //dereference, giving a U
(*(T*)(0)) * (*(U*)(0)) //the result of multiplying a U and a T
decltype(T(0)*U(0))
is equivalent only if T
and U
have constructors taking a single int
(or something which can be implicitly converted to from an integer literal).
The standard library already has a std::declval
to do this in a cleaner fashion:
decltype(std::declval<T>() * std::declval<U>())
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With