I am learning how to get type of the return value of overloaded function test() vs test(double).
I modified code from a SO answer (by chris).
#include <type_traits>
#include <utility>
int test();
double test(double x);
template<typename... Ts>
using TestType = decltype(test(std::declval<Ts>()...))(Ts...);
int main() {
std::result_of< TestType<double> >::type n = 0;
//^ ### compile error ###
using doubleDat = std::result_of< TestType<double> >::type ;
doubleDat n=0;
}
I got a compile error.
error: no type named 'type' in 'std::result_of'
As I understand:-
TestType<...>is "variadic template".
In my own words, it acts like a packed abbreviation that have any amount of parameters.The
TestType<double>is id of thetest(double)function.std::result_of<TestType<double>>::typeis the return type oftest(double).
doubleDatshould bedouble.
Question: Why it doesn't compile? How to solve it?
I have read these :-
- decltype for overloaded member function - no example about
std::result_of - c++: error: no type named ‘type’ in ‘class std::result_of<void (*(std::unordered_map - issue related to thread rather than
std::result_of
Clue: After a long search, I get faint smell that my code suffers "Most vexing parse".
Look at what your
TestType<double>expands to:test(std::decvlal<double>)isdoubleso you getdouble(double)result_of<double(double)>::typeasks if you can invoke adoublewith an argument of typedouble.The answer is no, because
doubleis not callable, so there's no nested type.You need to read the documentation for
result_ofto understand how to use it. The typeresult_of<F(Arg)>::typeis the result of invoking anFwith an argumentArg. IfFis callable with an argumentArgyou get the return type, if it is not callable with an argumentArgthen the nestedtypedoesn't exist.So this would work:
This creates an alias for a function of type
TestType<double>(i.e.double(double)) and then asks if you can invoke a pointer to that type (i.e.double(*)(double)) with an argument of typedouble. And you can, so you thetypeis valid.