Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does this syntax " decltype(*(T*)(0)**(U*)(0)) " mean?

Tags:

c++

c++11

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.

like image 424
Allanqunzi Avatar asked Sep 08 '15 15:09

Allanqunzi


1 Answers

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>())
like image 88
TartanLlama Avatar answered Oct 20 '22 19:10

TartanLlama