[英]use define to assign a struct member to another member of the same struct
typedef struct{
[..]
type_t member1;
type_t member2;
[...]
}structType_t
I want to assign member1 to member2. 我想将member1分配给member2。 As this is a repeated operation I thought of putting the assignmet in a #define:
由于这是重复的操作,因此我想到将Assignmet放在#define中:
#define op (structType_t).member1=(structType_t).member2
However, this seems to be wrong how would the compiler know that it is the members of the same struct and I can't see a way of using it. 但是,这似乎是错误的,编译器将如何知道它是同一结构的成员,而我看不到使用它的方法。 Any ideas?
有任何想法吗? I know I have other options such as macro or function but my question is this way possible?
我知道我还有其他选择,例如宏或函数,但是我的问题是这样吗?
Writing such macros is never a good idea. 编写这样的宏绝不是一个好主意。 It is probably not possible to write something better and more readable than
mystruct.member1 = mystruct.member2;
可能无法编写出比
mystruct.member1 = mystruct.member2;
更好,更易读的mystruct.member1 = mystruct.member2;
. 。
If you want to encapsulate this for whatever reason, use a function: 如果出于任何原因要封装它,请使用一个函数:
void structTypeMemberCopy (structType_t* obj)
{
obj->member1 = obj->member2;
}
This is likely going to get inlined and replaced with the equivalent of mystruct.member1 = mystruct.member2;
这很可能会内联并替换为等效的
mystruct.member1 = mystruct.member2;
in the machine code. 在机器代码中。
And finally there is the bad idea macro, which can be made type safe: 最后是一个坏主意宏,可以将其设置为安全类型:
#define structTypeCopy(obj) _Generic((obj), structType_t: (obj).member1 = (obj).member2)
...
structType_t mystruct = { ... };
structTypeCopy(mystruct);
You need to define the macro like this: 您需要这样定义宏:
#define a(T1) T1.n1 = T1.n2
the macro a
receive one parameter T1
and does the asignement. 宏
a
接收一个参数T1
并进行赋值。
Something like this: 像这样:
#include <iostream>
#define a(T1) T1.n1 = T1.n2
typedef struct {
int n1;
int n2;
} estructure;
int _tmain(int argc, _TCHAR* argv[])
{
estructure test;
test.n1 = 1;
test.n2 = 2;
a(test);
std::cout << test.n1 << " " << test.n2 << std::endl;
return 0;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.