Portability of std::mem_fun expression
Assuming a correct instantiation in the indicated comment, is the following expression legal and portable C++? Why or why not?
std::mem_fun</*…*/>(&a开发者_如何转开发mp;(std::vector<int>::clear))
As it's written, with an empty set of template parameters, no. You need to either give the correct parameters, or leave them out altogether so they're inferred from the argument.
So this is legal:
std::mem_fun(&std::vector<int>::clear)
and so is this:
std::mem_fun<void,std::vector<int> >(&std::vector<int>::clear)
Both give a function object with a function call operator that takes a pointer to a std::vector<int>
and calls clear
on it.
Edit: As UncleBens mentions, the parantheses around the function name are actually illegal, so I've removed them from my answer.
It is perfectly legal and portable. Remember only that on different platforms/compilers int might be different size. Also, the explicit parameter version is rarely used, let the compiler deduce the type itself.
No:
"ComeauTest.c", line 7: error: nonstandard form for taking the address of a member
function
std::mem_fun(&(std::vector<int>::clear));
^
Drop the extra parentheses.
In general I think the only purpose of std::mem_fun
is to deduce template parameters for you and choose to use either mem_fun_t
, mem_fun1_t
, const_mem_fun_t
or const_mem_fun1_t
, so it is unclear why you should ever want to specify the template parameters for mem_fun
explicitly. But naturally that is allowed, as with any other function template.
Short answer: "Some popular compilers no." (from Exceptional C++) (I will assume that he`s talking about GCC or Microsoft C++ Compiler).
The long answer is detailed here. I don`t know if the answer is still valid for the current compilers versions, because this post was published in 2004 with the book.
I strongly recommend you to read guru of the week (gotw.ca), there is a lot of interesting/funny/curious stuff there.
精彩评论