Matthew
Matthew

Reputation: 92

What types are types of in c?

I'm wondering what type types have in c. For example, how would I do something like this.

type type_a = int;
type type_b = float;

In context of my project, I'm trying to make a function that can be used as follows.

// createSelector(const char *name, ...)

Selector *mySelector = createSelector("myMethod", int, char);

// Selector->types contains all the passed types in an array.
// Selector->name contains the name of the method.

If c does not support this functionality, I can easily transfer my project to c++. However, I would then need to know what the type is in c++. Any help would be appreciated.

Upvotes: 2

Views: 376

Answers (4)

chrisaycock
chrisaycock

Reputation: 37928

As the others have mentioned, you can't refer directly to a type without reflection, which isn't a feature in C or C++. C++ at least has templates, which works for many generic algorithms.

But to answer your question for C, there is at least one library that attempts to provide this for its own needs. The Message-Passing Interface must send and receive data across many different platforms, where datatypes can be different sizes. So MPI uses constants to indicate the datatype as a function parameter. For example:

char buffer [BUFFERSIZE];
MPI_Send (buffer, BUFFERSIZE, MPI_CHAR, ...);  // MPI_CHAR indicates a char array

(It's worth noting that Boost's MPI bindings don't need the type constants and would just effectively call send(buffer).)

Hopefully you won't need to go down this road.

Upvotes: 2

Armen Tsirunyan
Armen Tsirunyan

Reputation: 133082

In addition to @Billy ONeal's answer I should note that compile-time type selection is possible in C++, by means of template metaprogramming

Upvotes: 3

user470379
user470379

Reputation: 4887

Both C and C++ do not allow you to directly work with types. To do the type of thing you're suggesting, you'll need to look into templates, although you probably won't be able to do exactly the type of thing you want but you might be able to get rather close.

// template <typename T, typename T2>
// Selector* createSelector(const char* name)
Selector *mySelector = createSelector<int,char>("myMethod");

Upvotes: 5

Billy ONeal
Billy ONeal

Reputation: 106609

You can't do that in either C or C++. The ability to perform such type-based introspection is called "Reflection", and it's simply not a feature in C or C++.

Honestly though, if you find yourself needing something like this you need to take an extremely long, hard look at your design -- needing things like this, even in those languages that support them is usually indicative of papering over a poor design.

Upvotes: 17

Related Questions