c - 通用值初始化分配器
问题描述
乱搞/学习 C。我想要一个将堆栈值移动到堆中的单行代码,这是我能想到的最好的。
#define defheapify(nm, T, sz) \
T* heapify_##nm (const T x) { \
T *nx = malloc(sz); \
nx[0] = x; \
return nx; \
}
defheapify(char, char, sizeof(char));
defheapify(uchar, unsigned char, sizeof(unsigned char));
defheapify(short_int, short int, sizeof(short int));
defheapify(ushort_int, unsigned short int, sizeof(unsigned short int));
defheapify(int, int, sizeof(int));
defheapify(uint, unsigned int, sizeof(unsigned int));
defheapify(long_int, long int, sizeof(long int));
defheapify(ulong_int, unsigned long int, sizeof(unsigned long int));
defheapify(long_long_int, long long int, sizeof(long long int));
defheapify(ulong_long_int, unsigned long long int, sizeof(unsigned long long int));
defheapify(float, float, sizeof(float));
defheapify(double, double, sizeof(double));
defheapify(long_double, long double, sizeof(long double));
它似乎工作:
short int *si = heapify_short_int(20);
printf("%d\n", ((int*)si)[0]); /* => 20 */
有没有更好的方法来实现这一点?
解决方案
因为这是 C:
void * heapify (const void *p, size_t sz) {
void *x = malloc(sz);
if (x) memcpy(x, p, sz);
return x;
}
然后,如果你坚持:
#define defheapify(nm, T, sz) \
T* heapify_##nm (const T x) { return heapify(&x, sz); }
但是,sz
如果你有,那就是多余的T
,所以:
#define defheapify(nm, T) \
T* heapify_##nm (const T x) { return heapify(&x, sizeof(x)); }
但是,如果您只关心问题中列出的类型,则可以改用_Generic
开关并简化界面。使用下面的代码,您可以消除找出正在处理的变量或常量类型的任务。只是总是打电话heapify_any
。
#define heapify_T(T, X) \
(T *)heapify(&(struct{ T x; }){X}.x, sizeof(T))
#define heapify_G(T, X) T:heapify_T(T, X)
#define heapify_any(X) _Generic( \
X, \
heapify_G(_Bool, X), \
heapify_G(char, X), \
heapify_G(signed char, X), \
heapify_G(unsigned char, X), \
heapify_G(short int, X), \
heapify_G(unsigned short int, X), \
heapify_G(int, X), \
heapify_G(unsigned int, X), \
heapify_G(long int, X), \
heapify_G(unsigned long int, X), \
heapify_G(long long int, X), \
heapify_G(unsigned long long int, X), \
heapify_G(float, X), \
heapify_G(double, X), \
heapify_G(long double, X), \
default:(void)0 \
)
在 C 中没有文字short
(或char
或_Bool
)值之类的东西,因此您需要一个变量或强制转换才能使用heapify_any
上面的宏。
short int *si = heapify_any((short)20);
printf("%hd\n", *si);
推荐阅读
- java - 在不改变另一个人的类的情况下,我如何要求它使用我的 Scanner 版本(作为内部类埋藏)而不是 java.util.Scanner?
- python - Python while 循环与单个等号 (=)
- android - 在 Kotlin 中使用带有 Comparator 的 Lambdas
- c++ - 将 -Wtype-limits 与类型泛型代码一起使用
- java - Android studio:如何动态显示和刷新同时水平和垂直方向的自定义列表?
- java - 如何使用java从mysql数据库返回多行
- python - 烧瓶:RunTimeError:线程中没有当前事件循环
- haskell - 如何使用 inline-c 包装返回指向自定义结构类型的指针的函数?
- github - GitHub 包注册表 NPM 400 放置错误
- python - Pandas:如何聚合多个列?