Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there something in C like C++ templates? If not, how to re-use structures and functions for different data types?

Tags:

c

I want to write a linked list that can have the data field store any build-in or user-define types. In C++ I would just use a template, but how do I accomplish this in C?

Do I have to re-write the linked list struct and a bunch of operations of it for each data type I want it to store? Unions wouldn't work because what type can it store is predefined.

like image 747
Rachel Avatar asked Sep 13 '11 20:09

Rachel


People also ask

Are there templates in C?

The main type of templates that can be implemented in C are static templates. Static templates are created at compile time and do not perform runtime checks on sizes, because they shift that responsibility to the compiler.

How many types of templates are there in C++?

There are three kinds of templates: function templates, class templates and, since C++14, variable templates. Since C++11, templates may be either variadic or non-variadic; in earlier versions of C++ they are always non-variadic.

What is the use of templates in C++?

What is Templates in C++? Templates in C++ is an interesting feature that is used for generic programming and templates in c++ is defined as a blueprint or formula for creating a generic class or a function. Simply put, you can create a single function or single class to work with different data types using templates.

What are oop templates?

A template is a piece of code that can be copied and modified to fit a specific situation. Some templates show how, why, and when to use some feature of the language. Some templates show how to implement design patterns.


1 Answers

There's a reason people use languages other than C.... :-)

In C, you'd have your data structure operate with void* members, and you'd cast wherever you used them to the correct types. Macros can help with some of that noise.

like image 138
Ned Batchelder Avatar answered Oct 21 '22 05:10

Ned Batchelder