Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any way to get the return type of the "current function"

I would like to write a template that would get as a parameter the return type of the function in which it is being instantiated.

For example, assume I've a Result templated class:

template<type T>
class Result {
    T _result_value;
    T& operator=( T that );
    ~Result( );
}

There would be several specializations for this class. In the destructor I would like to log the return type, and within the operator= assignment I would like to check and assert for error values.

Ideally, I would like to be able to have such a define:

#define RESULT Result< /* decltype magic for type of current function */ >

so I could use it:

HFILE MyOpenFile( ... ) {
    RESULT result;
}

...which will be deduced to Result<HFILE>. This is a simplified example: writing RESULT instead of Result<HFILE> isn't a big deal, but there are other scenarios where the return type of the current function isn't easily obtained.

like image 964
Uri Avatar asked Nov 08 '12 09:11

Uri


People also ask

What is the return type of this function?

The result of a function is called its return value and the data type of the return value is called the return type. If a function declaration does not specify a return type, the compiler assumes an implicit return type of int .

Can functions return any type?

A function may be defined to return any type of value, except an array type or a function type; these exclusions must be handled by returning a pointer to the array or function. When a function does not return a value, void is the type specifier in the function declaration and definition.

What is the return type of new?

Since new is a language keyword and not a function, it doesn't "return" anything.

Should I use exit or return?

Return uses exit code which is int value, to return to the calling function. Using the return statement in the main function means exiting the program with a status code; for example, return 0 means returning status code 0 to the operating system.


1 Answers

No. There's nothing in C++ which refers to the "current function". The closest is __func__ but that's a string literal. Hence, there's nothing to pass to decltype.

Not that you need it, with auto.

like image 183
MSalters Avatar answered Oct 22 '22 15:10

MSalters