960716 - 如何将void视为参数? [英] 960716 - how to treat void as argument?
问题描述
在以下代码中:
In the following code:
void f()
{
int a=2, b=3;
M(a+1);
M(swap(a,b));
}
我正在寻找这样的输出:
a + 1 - > 3
swap(a,b) - > x
假设交换是一个交换a和b的值并返回void的函数。
如何写M宏?
In换句话说,我需要结果如果无效,它不会在第二列中输出除x以外的任何内容,如果它不是无效则显示结果。
< b>我尝试了什么:
模板函数和可变参数宏。
I'm looking for such an output:
a+1 --> 3
swap(a,b) --> x
Assume swap is a function which swaps the values of a and b and returns void.
How to write the M macro?
In another words, I need the result if void, it doesn't output anything other than x in the second column and if it's not void it shows the result.
What I have tried:
template functions and variadic macros.
推荐答案
如何将void视为参数?
how to treat void as argument?
我的简答:你没有!
基本上,在C / C ++语言中,'void'表示没有价值。
My short answer: you don't!
Basically, in C/C++ language, 'void' means no value.
假设swap是一个交换a和b的值并返回void的函数。
Assume swap is a function which swaps the values of a and b and returns void.
在你的情况下,'void'用来表示一段代码没有返回任何值。
In your situation, 'void' is used to say that a piece of code do not return any value.
1。很多程序都是用void main(void)编写的,可以做很多事情!
1. many programs are written with void main(void) which do many things!
第一个 void
表示 main
不向调用者返回任何值,调用者是操作系统,它不关心返回值。
秒 void
表示 main
没有从来电者那里收到任何价值。
Void类型 - 维基百科 [ ^ ]
First void
means that main
do not return any value to caller, and the caller is the OS and it don't care about a return value.
Second void
means that main
do not receive any value from caller.
Void type - Wikipedia[^]
class variant
{
char d_var[80];
public:
variant() { d_var[0] = 0; }
variant(int a) { sprintf(d_var, "%d", a); }
variant(LPCSTR var) { strcpy(d_var, var); }
operator LPCSTR() const { return d_var; }
//string operator ,(const string &arg) const { return d_var; }
};
string operator ,(const variant &var, const string &arg) { return var; }
void void_func() {}
struct PrintHelper
{
operator string() const { return "void"; }
} printHelper;
void print(LPCSTR title, const string &result)
{
printf("expression \"%s\" evaluates to \"%s\"\n", title, result.c_str());
}
#define M(expr) print(#expr, (expr, printHelper))
void f9()
{
int a=2, b=3;
M(10);
M(a+1);
M(void_func());
M(swap(a,b));
}
输出到:
It outputs to:
expression "10" evaluates to "10"
expression "a+1" evaluates to "3"
expression "void_func()" evaluates to "void"
expression "swap(a,b)" evaluates to "void"
现在我可以打印一个表达式以及它所评估的值。它支持void值,并且无论值是否被评估为void都没有区别。
现在我想知道代码中为什么运算符在被定义为类变体成员函数时不起作用。它显然不应该与定义为类外的自我决定运算符的时间不同。
Now I could print an expression as well as the value it evaluates to. It supports void values and doesn't differ whether a value is evaluated to void or not.
Now I wonder in the code, why operator , doesn't work when it's defined as a class variant member function. It apparently shouldn't differ from when is defined as a self-determining operator outside of the class.
这篇关于960716 - 如何将void视为参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!