简体   繁体   English

std :: mem_fun表达式的可移植性

[英]Portability of std::mem_fun expression

Assuming a correct instantiation in the indicated comment, is the following expression legal and portable C++? 假设指示的注释中的实例正确,以下表达合法且可移植的C ++吗? Why or why not? 为什么或者为什么不?

std::mem_fun</*…*/>(&(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. 两者都给函数对象提供了一个函数调用运算符,该运算符采用指向std::vector<int>的指针并对其进行clear

Edit : As UncleBens mentions, the parantheses around the function name are actually illegal, so I've removed them from my answer. 编辑 :正如UncleBens提到的那样,函数名周围的括号实际上是非法的,因此我从答案中删除了它们。

It is perfectly legal and portable. 这是完全合法且可移植的。 Remember only that on different platforms/compilers int might be different size. 请记住,在不同的平台/编译器上,int的大小可能不同。 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. 总的来说,我认为std::mem_fun的唯一目的是为您推导模板参数并选择使用mem_fun_tmem_fun1_tconst_mem_fun_tconst_mem_fun1_t ,因此目前尚不清楚为什么要为mem_fun明确指定模板参数。 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). (来自Exceptional C ++)(我假设他在谈论GCC或Microsoft C ++编译器)。

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. 我不知道答案是否仍然对当前的编译器版本有效,因为该帖子于2004年随该书一起发布。

I strongly recommend you to read guru of the week (gotw.ca), there is a lot of interesting/funny/curious stuff there. 我强烈建议您阅读本周的大师(gotw.ca),那里有很多有趣/有趣/好奇的东西。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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