简体   繁体   中英

Why can't a return type be function type but function pointer in c++?

int method1() {
    return 0;
}

decltype(method1) method2() {
    return method1;
}

I compile my code,get an error: 'method2' declared as function returning a function, then I change the return type to function pointer,it works,I just want to why it is so.

decltype(method1) *method2() {
    return method1;
}

In C++, functions and arrays cannot be returned. It is how the language is designed.

You have to return either pointer or reference to them. You've already tried with pointer, which works. The following, which returns reference, should also work:

decltype(method1)& method2() {
   return method1;  
}

What code do you want the compiler to return when it returns a "function"? Do you want the machine code returned?

There's no way for a compiler to do this sanely. Besides, since you probably don't want self-modifying code, you don't really want a copy of the code. Instead it is possible to return the address of a function.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM