Bruce
Bruce

Reputation: 35213

How to find the return type of a function?

So __FUNCTION__ tells us the name of the current function. Is there a similar macro for return type of the function?

Upvotes: 3

Views: 771

Answers (4)

MSalters
MSalters

Reputation: 179779

C++11:

template < typename R, typename ...Args >
char const* FunctionReturnTypeAsString( R foo(Args...) ) {
  return typeid(R).name()
}

Upvotes: 1

Xeo
Xeo

Reputation: 131779

If you don't need it at preprocessing time:
In C++0x, you can do use decltype(myFunc(dummyparams)), which stands for the return type of myFunc (compile-time).
If you now want a string out of that, enable RTTI (run-time type information) and use typeid().name() (run-time):

#include <typeinfo>

double myFunc(){
  // ...
  return 13.37;
}

int main(){
  typedef decltype(myFunc()) myFunc_ret;
  char const* myFunc_ret_str = typeid(myFunc_ret).name();
}

Note, however, that the myFunc_ret_str isn't always a clean name of the return type - it depends on how your compiler implements typeid.

Upvotes: 2

sharptooth
sharptooth

Reputation: 170479

Since you already use a Visual-C++ specific __FUNCTION__ macro you could look into __FUNCSIG__ macro - it expands into the full signature which you could then parse and extract the return type. There's no macro that would do that on itself in Visual C++.

Upvotes: 4

Sarfaraz Nawaz
Sarfaraz Nawaz

Reputation: 361252

Seeing the function itself you can know the return type. After all, MACRO works even before compile time, that means, when you write the MACRO you do know the return type of the function only if you look at it.

If I tell you that you can use __FUNCSIG__, even then you do know the return type at the moment you use it in your code.

However if you need to know it in template programming, then I would suggest you to look at : decltype

Upvotes: 1

Related Questions