简体   繁体   English

为什么我会调用函数名称包含在parens中的函数?

[英]why would I call a function with the function name wrapped in parens?

I recently came across code that looked like this: 我最近遇到的代码看起来像这样:

void function(int a, int b, int c){
  //...
}

int main(){
  //...
  (function)(1,2,3);
  //...
}

What is the point of wrapping the function name separately in parens? 在parens中单独包装函数名称有什么意义?
Does it have any affect that would be different than function(1,2,3); 它是否有任何与function(1,2,3);不同的影响function(1,2,3); ?

Why does the language allow such syntax? 为什么语言允许这样的语法?

The only case I can think of where it would matter is when function is defined as a macro. 我能想到的唯一情况是将function定义为宏。

In C, standard library functions may also be implemented as function-like macros (for efficiency). 在C中,标准库函数也可以实现为类似函数的宏(为了效率)。 Enclosing the function name in parentheses calls the actual function (since the function name is not followed by a ( ). 将函数名括在括号中会调用实际函数(因为函数名后面没有( )。

As for why the language allows the syntax, a function call consists of an expression of pointer-to-function type followed by the arguments in parentheses. 至于语言允许语法的原因,函数调用包含指向函数类型的表达式,后跟括号中的参数。 In most cases, the prefix is a function name (which is implicitly converted to a pointer to the function), but it can be an arbitrary expression. 在大多数情况下,前缀是函数名称(它隐式转换为指向函数的指针),但它可以是任意表达式。 Any expression may be enclosed in parentheses, usually without changing its meaning (other than affecting precedence). 任何表达式都可以括在括号中, 通常不会改变其含义(除了影响优先级)。 (But see Jonathan Leffler's comments for some counterexamples.) (但请参阅Jonathan Leffler对一些反例的评论。)

In addition to suppressing function-like macro expansions, wrapping an unqualified function name in parentheses suppresses argument-dependent lookup . 除了抑制类似函数的宏扩展之外,在括号中包装非限定函数名还会抑制依赖参数的查找 For example: 例如:

namespace meow {
    struct kitty {};
    void purr(kitty) {}
}

int main() {
    meow::kitty stl;
    purr(stl); // OK, ADL finds meow::purr
    (purr)(stl); // error; no ADL is performed
}

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

相关问题 我是否检查是否存在具有或不具有parens的宏功能? - Do I check the existence of a macro function with or without the parens? 我如何获得函数中参数的名称 - How would I get the name of the parameters in a function auto 使用括号是否意味着 function 原型? - Can auto using parens mean a function prototype? 为什么*¶m会在函数中使用? - Why would *&param be used in a function? 为什么__FUNCTION__是不确定的? - Why would __FUNCTION__ be undefined? 为什么虚函数是私有的? - Why would a virtual function be private? 为什么我没有得到匹配的 function 来电 - Why am I getting no matching function for call to 为什么使用模板函数会收到“没有匹配的函数来调用'...'”? - Why am I getting “no matching function for call to '…'” with template function? 为什么对于可变参数模板函数,我得到“没有匹配的函数调用 ..”? - Why am I getting "no matching function for call to .." for the variadic template function? 为什么类方法不能使用相同的名称调用全局函数? - Why can't a class method call a global function with the same name?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM