问题描述
当一个函数没有任何参数时,可以通过 define
as
When a function does not have any argument, it is possible to call it without parenthesis by define
as
#define test test()
是否可以在不带括号的情况下调用带有参数的函数?像
Is it possible to call a function with argument without paranthesis? Something like
#define test test(char *arg)
test "argument 1";
推荐答案
在C语言中,这是不可能的.标准(C99)的6.5.2节描述了后缀表达式,并且没有类似的语法.函数调用为(§6.5.2.2):
That's not going to be possible in C the way you have it. §6.5.2 of the standard (C99) describes postfix expressions, and has no syntax like that. Function calls are (§6.5.2.2):
括号不是可选的,它们需要包装所有参数,因此您需要一个类似函数的宏(在调用"站点需要括号)或两个单独的东西(一个用于插入起始括号,一个用于插入).插入结束符).
Parens are not optional, and they need to wrap all the arguments so you need either a function-like macro (which requires parens at the "call" site) or two separate things (one to insert the starting paren, one to insert the closing one).
您可以这样做:
#define test puts(
#define end );
#define int_proc int
#define proc_body {
#define proc_end }
#define no_args (void)
#include <stdio.h>
int_proc main no_args
proc_body
test "hello" end
proc_end
但是...真的吗?
C ++特别提供了运算符重载的更多可能性.如果您要自定义"某些语法,则可能需要调查一下.
C++ offers more possibilities with operator overloading in particular. You might want to look into that if you want to "customize" some syntax.
这是一个可怕的例子:
#include <iostream>
struct Foo {
void operator=(char const* str)
{
std::cout << str << std::endl;
}
};
Foo global_foo;
#define test global_foo =
int main()
{
test "hello";
}
请注意,您可能会发现一些明智的方法,例如Qt的 qDebug
实用工具类.从示意图上看,它是这样的:
Note that there are sane approaches that you might find attractive, e.g. Qt's qDebug
utility class. Schematically, it goes like this:
#include <iostream>
struct debug {
debug() {}
~debug()
{
std::cout << std::endl;
}
debug const& operator<<(char const* msg) const
{
std::cout << msg << " ";
return *this;
}
};
通常的使用方式是:
debug() << "this" << "works";
如果您添加采用 char const *
的构造函数:
If you add a constructor that takes char const*
:
debug(char const*msg)
{
std::cout << msg << " ";
}
然后,您可以使用强制转换符号并编写:
Then you can use cast notation and write:
(debug) "Hello";
与您所拥有的(和可宏化的)非常接近.
Which is pretty close to what you had (and is macroable).
然后,您可以与所有其他运算符( operator,
将是主要的候选对象)结合在一起,但是优先规则可能会破坏这种乐趣.
Then you can get fancy with all the other operators (operator,
would be a prime candidate), but precedence rules might ruin the fun a bit.
这篇关于在C中使用不带括号的参数调用函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!