在C中调用带参数但没有括号的函数?

Goo*_*bot 2 c function

当一个函数没有任何参数时,可以用defineas 括号来调用它

#define test test()
Run Code Online (Sandbox Code Playgroud)

是否可以在没有paranthesis的情况下调用带参数的函数?就像是

#define test test(char *arg)

test "argument 1";
Run Code Online (Sandbox Code Playgroud)

Mat*_*Mat 13

在你拥有C的方式中,这是不可能的.标准(C99)的§6.5.2描述了后缀表达式,并且没有这样的语法.函数调用是(§6.5.2.2):

后缀表达式后跟()包含可能为空的逗号分隔表达式列表的括号是函数调用.后缀表达式表示被调用的函数.表达式列表指定函数的参数.

Parens不是可选的,它们需要包装所有参数,因此您需要一个类似函数的宏(需要在"call"站点上的parens)或两个单独的东西(一个用于插入起始paren,一个用于插入关闭一).

你可以这样做:

#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
Run Code Online (Sandbox Code Playgroud)

但是......真的吗?

特别是C++为运算符重载提供了更多可能性.如果要"自定义"某些语法,可能需要研究一下.

这是一个可怕的例子:

#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";
}
Run Code Online (Sandbox Code Playgroud)

请注意,您可能会发现有吸引力的方法,例如Qt的qDebug实用程序类.原理上,它是这样的:

#include <iostream>

struct debug {
    debug() {}
    ~debug()
    {
        std::cout << std::endl;
    }
    debug const& operator<<(char const* msg) const
    {
        std::cout << msg << " ";
        return *this;
    }
};
Run Code Online (Sandbox Code Playgroud)

通常使用它的方法是:

debug() << "this" << "works";
Run Code Online (Sandbox Code Playgroud)

如果添加构造函数,则需要char const*:

debug(char const*msg)
{
    std::cout << msg << " ";
}
Run Code Online (Sandbox Code Playgroud)

然后你可以使用强制表示法并写:

(debug) "Hello";
Run Code Online (Sandbox Code Playgroud)

这与你拥有的非常接近(并且是可以宏的).

然后你可以看到所有其他运算符(operator,将是一个主要候选者),但优先规则可能会破坏一些乐趣.