Unsolved Return type of lambda function
-
@JonB , Thanks for the update.. I got the point.
-
I cannot remember everything I was doing here, but I was testing if getting the return type would invoke the lambda. I think it will not and it will give you the return type. You will have to search online the other crap I was testing here as I don't remember:
{ auto func = [](int a){ qInfo() << "Invoked"; return a; }; auto a = func(1); qInfo() << typeid(a).name(); decltype (a) b; qInfo() << typeid(b).name(); qInfo() << typeid(func(1)).name(); }
Types returned by typeid are compiler specific if I remember correctly. So it would not be suitable for cross platform code unless you can ensure the same compiler everywhere.
-
There's
std::invoke_result
for that purpose. It goes like this (more or less):auto x1 = [](int i) -> int { return i; }; typedef typename std::invoke_result<decltype(x1), int>::type x1ret_type; //< which is int
-
This is interesting:
{ auto x1 = [](int i) -> int { qInfo() << "Invoked"; return i; }; typedef typename std::invoke_result<decltype(x1), int>::type x1ret_type; typedef decltype (x1(1)) rtype; Q_ASSERT(typeid(rtype) == typeid(x1ret_type)); qInfo() << typeid(rtype).name() << typeid(x1ret_type).name(); }
-
-
I didn't know if decltype would not execute the function to get the return type. I was playing with it. I knew typeid did, didn't know about decltype. So the two methods produce the same output.
-
@fcarney said in Return type of lambda function:
I didn't know if decltype would not execute the function to get the return type.
It would if it could but it can't so it shan't.
decltype
is evaluated at compile time, so there's no way it could or would execute a function (unless the function is also evaluated at compile time, which it isn't here). On the other handtypeid
is a runtime-executed operator. -
@kshegunov Just to be clear, I think I was not clear, typeid does NOT execute the function to find the return type either. I think I said it strangely.
-
@fcarney said in Return type of lambda function:
@kshegunov Just to be clear, I think I was not clear, typeid does NOT execute the function to find the return type either. I think I said it strangely.
Are you sure? That'd be odd.
-
{ auto x1 = [](int i) -> int { qInfo() << "Invoked"; return i; }; typedef typename std::invoke_result<decltype(x1), int>::type x1ret_type; typedef decltype (x1(1)) rtype; Q_ASSERT(typeid(rtype) == typeid(x1ret_type)); qInfo() << typeid(rtype).name() << typeid(x1ret_type).name(); qInfo() << "before typeid"; typeid(x1(1)); qInfo() << "after typeid"; }
Pretty sure, I saw this behavior before (tested again):
i i before typeid after typeid