Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
237 views
in Technique[技术] by (71.8m points)

c++ - What are the rules for function pointers and member function pointers to Standard functions?

What are the existing rules for taking function pointers or member function pointers to Standard functions? For example, something like

auto p = &std::string::size;

Is this legal? Would it be more or less legal if I explicitly requested the correct type, so it would function even if there was an additional implementation-added overload of std::string::size?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Using the "correct" type doesn't make things better: Except for the virtual functions all functions in the standard C++ library can have additional arguments as long as these are defaulted. Since the functions can also be declared with additional overloads (again with the exception of the virtual function), you can end up trying to assign an overload set a variable. Thus, the code isn't portable and there is no way to make it portable by using some sort of cast or some signature instead of auto.

The relevant quote is 17.6.5.5 [member.functions] paragraph 1:

An implementation may declare additional non-virtual member function signatures within a class:
--- by adding arguments with default values to a member function signature;
— by replacing a member function signature with default values by two or more member function signatures with equivalent behavior; and
— by adding a member function signature for a member function name.

I don't see a similar permission for non-member functions, though. Not sure where the permission to mess with these is hiding but I'm relatively sure that there are some weasel words for these as well. Looking further, it seems non-member functions are more constrained according to 17.6.5.4 [global.functions] paragraph 3:

An implementation shall not declare a global or non-member function signature with additional default arguments.

This would imply that you can take the address of the non-member functions, at least, when specifying the desired signature.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...