问题描述
从OO(C#,Java中,斯卡拉)即将我的价值非常高的两个code重用和类型安全的原则。类型参数在上面的语言做的工作,使它们都是类型安全的,不'浪费'code。
Coming from OO (C#, Java, Scala) I value very highly the principles of both code reuse and type-safety. Type arguments in the above languages do the job and enable generic data structures which are both type-safe and don't 'waste' code.
在我陷到C,我知道我不得不作出妥协,我想它是正确的。无论是我的数据结构中的每个节点/元素的无效*
和我失去的类型安全或者我必须重新写我的结构和code为每种类型我想将它们与使用。
As I get stuck into C, I'm aware that I have to make a compromise and I'd like it to be the right one. Either my data structures have a void *
in each node / element and I lose type safety or I have to re-write my structures and code for each type I want to use them with.
表示code的复杂性是一个明显的因素:通过数组或一个链表迭代是微不足道并添加 *下一
来一个结构没有额外的努力;在这些情况下是有意义不要试图和再利用结构和code。但对于更复杂的结构,答案就不那么明显了。
The complexity of the code is an obvious factor: iterating through an array or a linked-list is trivial and adding a *next
to a struct is no extra effort; in these cases it makes sense not to try and re-use structures and code. But for more complicated structures the answer isn't so obvious.
还有模块化和可测试性:分离出从使用结构code类型和操作,使测试更容易。反过来也是如此:一些测试code的迭代过的结构,而它试图做其他的事情就会变得混乱
There's also modularity and testability: separating out the type and its operations from the code that uses the structure makes testing it easier. The inverse is also true: testing the iteration of some code over a structure whilst it's trying to do other things gets messy.
那么,什么是你的建议吗? 无效*
和重用或类型安全和重复code?是否有任何一般原则是什么?我在试图迫使OO程序上时,它不适合?
So what's your advice? void *
and reuse or type-safety and duplicated code? Are there any general principles? Am I trying to force OO onto procedural when it won't fit?
修改:请不要推荐C ++,我的问题是关于C
Edit: Please don't recommend C++, my question is about C!
推荐答案
我想说的使用无效*
这样你就可以重新使用code。这是更多的工作来如重新实现一个链表,而不是确保你获取/设置列表中的数据正确。
I would say use void *
so you can re-use the code. It's more work to re-implement e.g. a linked list, than to make sure you get/set the data in the list properly.
从拿尽可能多的提示,我觉得他们的数据结构非常好,易于使用,并产生了,因为类型安全的损失小麻烦。
Take as many hints from glib as possible, I find their data structures very nice and easy to use, and have had little trouble because of the loss of type safety.
这篇关于泛型VS类型安全?在C使用无效*的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!