I compiled the following cords with g++
#include <iostream>
#include <string>
using namespace std;
template<class T>
class Node<const char*>{
private:
string x_;
Node* next_;
public:
Node (const char* k, Node* next):next_(next),x_(k){}
string data(){return x_;}
Node *get_next(){return next_;}
};
$ g++ -c node01.cc
node01.cc:5: error: ‘Node’ is not a template
What’s wrong?
I’m begginer for c++
You’re mixing up declarations and instantiations. When you declare a template, you don’t specify a type immediately after its name. Instead, declare it like this:
Your original declaration also confuses
string,const char *, and generic types that should be in terms ofT. For a template like this, you probably want to let the user define the type of the member (x_). If you explicitly declare it asconst char *orstring, you’re losing genericity by limiting what the user can use forT.Notice that I changed the types of the instance variables, the parameters of the constructor and the return type of
data()to be in terms ofT, too.When you actually instantiate a variable of the template type, you can provide a concrete type parameter, e.g.:
Whenever you write the template name
Nodeoutside the template declaration, it’s not complete until you provide a value for the parameterT. If you just sayNode, the compiler won’t know what kind of node you wanted.The above is a little verbose, so you might also simplify it with a typedef when you actually use it:
Now you’ve built a linked list of two nodes. You can print out all the values in the list with something like this:
If all goes well, this will print out: