Question_Guy
Question_Guy

Reputation: 333

Equivalent of std::pair in C

What is the C equivalent of std::pair from C++? I'm trying to find the equivalent on the web and can't find anything but explanations of what it does.

Upvotes: 4

Views: 20011

Answers (4)

ichramm
ichramm

Reputation: 6642

std::pair in C++:

template <class t1, class t2>
struct pair {
  t1 first;
  t2 second;
}

std::pair takes advantage of templates, so each concrete instantiation defines a new class std::pair<myT1, myT2>.

There's no such thing in C, you may have to declare a different struct each time, or use void *...

struct pair {
  struct myT1 first;
  struct myT2 second;
}

Upvotes: 3

Educorreia
Educorreia

Reputation: 440

As other answers made clear, C doesn't have anything similar to C++ templates.

However, you may use void* as a way to store addresses of variables of any type, by casting to a pointer of the data type you want.

Following this, a possible implementation of a pair structure in C would be as follows:

struct pair {
    void* first;
    void* second;
};

Upvotes: 0

Andreas Grapentin
Andreas Grapentin

Reputation: 5796

While the other answers are correct in saying that C does not have templates, the assumption that you can not have a generic pair type is wrong. If you really need a generic type, that is, you don't want to manually define a struct for each pair of types you want to use a pair for, you are left with 3 options.

Firstly, you could use a struct containing two void* types, and use these pointers as generic storage pointers for you data. (This is needlessly complicated and I would not generally recommend it)

Secondly, if the amount of types for your pair structure is known beforehand, you could use a union in your struct, for example

struct pair 
{
  union
  {
    int first_int;
    float first_float;
  };
  union
  {
    int second_int;
    float second_float;
  }
}

Or thirdly, you could use parametric macros to generate struct definitions of types you need, without constantly repeating yourself.

Or, alternatively think of a way to write your code that does not rely on templated types.

Upvotes: 5

Mike Seymour
Mike Seymour

Reputation: 254461

There isn't one. std::pair is a template, and C doesn't have anything similar to templates.

For a given specialisation of the template, you can define a structure that's more or less equivalent; so that std::pair<int, double> is similar to

struct pair_int_double {
    int first;
    double second;
};

but you've chosen the wrong language if you want a generic template.

Upvotes: 21

Related Questions