Defining a node of a linked-list using std::pair sounds as simple as drinking a Starbucks's white chocolate mocha. But it really isn't. Give it a try! The constraint is to use std::pair's first or second as a pointer to the structure itself, like in any linked-list's node. As far as I know, it is impossible unless you resort to ugly casts from void pointers. The problem is actually quite well known and gives rise to something known as infinite regress, where the problem you want to solve reappears in the solution to the problem.

typedef std::pair<int, /* Pointer to this pair!! */ > Node;

The closest thing I could come up with is something like the one below.

struct Node : std::pair <int, Node *>

{};

Node n;

n.second = &n; // A cyclic linked-list.

## Sunday, August 31, 2008

Subscribe to:
Post Comments (Atom)

## 5 comments:

In C++0x:

template <typename T> using Node = std::pair<T, Node*>;

How does this grab you?

template <class <typename A, typename B> T, typename First>

struct Mu2 {

T<First, Mu2<T, First>* > mu;

};

Mu2<std::pair, int> m;

m.mu.second = &m;

It's not exactly what you asked for, but it is arguably closer than the solution with inheritance.

It almost gave me a neck sprain, but it works! I've reorganized and simplified it a little.

template <template <typename, typename> class T, typename First>

struct Mu2

{

T<First, Mu2* > mu;

};

Cool stuff, can you check out my C++ Code Samples too?

if you like c++ you can compile it online here: http://codecompiler.info/

32, 64 - windows & Linux - and more programming languages

Post a Comment