Dereferencing a function with default arguments - C++14 vs C++11

大城市里の小女人 提交于 2019-12-06 18:33:24

问题


Following code can't be compiled with g++ version 5.4.0 with option -std=c++1y:

void f(int=0) ;

int main() {
    f(); // ok
    (*f)(2);// ok
    (*f)();// ok c++11; error with c++14: too few arguments to function
    return 0;
}

The function declared to have default argument, so what is wrong here? thanks for help.

And why does g++ -c -std=c++11 compile?


回答1:


Accepting (*f)() as valid is a GCC bug. The letter of the standard indicates that using a function name with unary * should cause the function name to decay into a pointer. The pointer should then be dereferenced to obtain the functions address for the call expression.

But GCC seems clever, and omits the above behavior. It treats (*f) simply as f. And calling f can be done with default arguments.

However, one can force GCC to preform the decay. Unary + applied on the function name will decay it to a pointer forcefully. So the following two:

(+f)();
(*+f)();

Cause GCC to emit error: too few arguments to function on either standard revision, in both GCC 7.2 and GCC 6.3.




回答2:


Default arguments are not a part of function type, so they are discarded when you implicitly convert function to function pointer and then indirect that pointer.



来源:https://stackoverflow.com/questions/47013385/dereferencing-a-function-with-default-arguments-c14-vs-c11

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!