Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I write a function type that returns a function?

The following fails to compile on both gcc and clang

#include <type_traits>

int foo();

int main()
{
    using R = std::result_of_t<decltype(foo)()>; // error
}

The error on both compilers deals with the illegality of declaring a function returning a function. But I'm not declaring such a function - I'm just trying to write its type - since that's what result_of expects. Is this really still ill-formed?

like image 884
Barry Avatar asked Mar 07 '16 15:03

Barry


People also ask

Can a function return a function?

A function is an instance of the Object type. You can store the function in a variable. You can pass the function as a parameter to another function. You can return the function from a function.

Can a function return a 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.

Can a function return a type TypeScript?

We can return any type of value from the function or nothing at all from the function in TypeScript. Some of the return types is a string, number, object or any, etc. If we do not return the expected value from the function, then we will have an error and exception.

What is the return type of type () function?

type() method returns class type of the argument(object) passed as parameter in Python.


1 Answers

You're passing a type-id, which is defined in [dcl.name] as

[…] syntactically a declaration for a variable or function of that type that omits the name of the entity. […] It is possible to identify uniquely the location in the abstract-declarator where the identifier would appear if the construction were a declarator in a declaration. The named type is then the same as the type of the hypothetical identifier.

For the hypothetical identifier to have some type, the hypothetical declaration must be well-formed in the first place. But it isn't as per [dcl.fct]/10. Hence the program is ill-formed (and the compilers' error messages are actually comprehensible). This case is also more directly covered by [temp.deduct]/(8.10), implying that this is a (SFINAE-friendly) error.


In fact, merely implying an invalid type's usage suffices to make the program ill-formed. E.g. creating the type pointer to function returning function is ill-formed:

using f = int();
using t = f(*)();

So is the following:

struct A {virtual void f() = 0;};
using t = A(*)();

(Clang shouldn't be accepting this. C.f. GCC bug 17232's interesting discussion).

like image 80
Columbo Avatar answered Oct 01 '22 22:10

Columbo