Self reference in Template class?

N

nw

Hi comp.lang.c++,

I have the following header (simple.h):

#ifndef SIMPLE
#define SIMPLE

template<class _prec=double>
class Simple {

public:

Simple() {
}

Simple<_prec> next;
};

#endif

and c++ file:

#include <iostream>
#include "simple.h"

using namespace std;

int main() {
Simple<double> s;
}


Compilation gives me the error:

simple.h: In instantiation of 'Simple<double>':
simple.cpp:7: instantiated from here
simple.h:12: error: 'Simple<_prec>::next' has incomplete type
simple.h:5: error: declaration of 'class Simple<double>'

under g++ 4.1.2. I guess I need to add a prototype for Simple, but I
can't quite see how to do this for a template class. Any help
appreciated!
 
F

Fei Liu

nw said:
Hi comp.lang.c++,

I have the following header (simple.h):

#ifndef SIMPLE
#define SIMPLE

template<class _prec=double>
class Simple {

public:

Simple() {
}

Simple<_prec> next;
};

#endif

and c++ file:

#include <iostream>
#include "simple.h"

using namespace std;

int main() {
Simple<double> s;
}


Compilation gives me the error:

simple.h: In instantiation of 'Simple<double>':
simple.cpp:7: instantiated from here
simple.h:12: error: 'Simple<_prec>::next' has incomplete type
simple.h:5: error: declaration of 'class Simple<double>'

under g++ 4.1.2. I guess I need to add a prototype for Simple, but I
can't quite see how to do this for a template class. Any help
appreciated!

You cannot do this. Declare next as a pointer or reference type (and
make sure the pointee is always valid of course during runtime).

Fei
 
P

Puppet_Sock

Hi comp.lang.c++,

I have the following header (simple.h):

#ifndef SIMPLE
#define SIMPLE

template<class _prec=double>
class Simple {

public:

  Simple() {
  }

  Simple<_prec> next;

};

#endif
[snip]

Um. Is that going to work?

You make an object of type Simple<x>. It has a data member
of type Simple<x>. That data member has a data member of
type Simple<x>. And so on. Eventually the two little girls
from "The Shining" come out and ask you to come play with
them "forever and ever and ever."

Possibly you want a pointer as data member?
Socks
 
N

nw

You make an object of type Simple said:
of type Simple<x>. That data member has a data member of
type Simple<x>. And so on. Eventually the two little girls
from "The Shining" come out and ask you to come play with
them "forever and ever and ever."

Possibly you want a pointer as data member?

uh yea, I didn't think this though.

Definitely don't want to invoke room 237, will refactor.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,999
Messages
2,570,243
Members
46,836
Latest member
login dogas

Latest Threads

Top