2

I'm working on an assignment where I create my own container using templates. The container I am required to use is called Smaph, which takes in two pairs of numbers and does a variety of functions with them. I am only allowed to make a header file for this assignment. I've created a singly-linked class slink, that takes one template argument.

Currently, I am trying to get a feel for templates and learning how to use them, so I have a very simple example I was hoping you could help me with. I have a push_back function in my singly linked list class to add to my templates. For some reason, I can't add things to my slink because I get a compile time error that says, Invalid use of member function, (push_back), did you forget the ( )? Can someone explain to me why I am getting this error? Thank you!

template <typename T>
class slink {
  private:
    struct node {
    T datum;
    struct node *next;
    };
    node *head, *tail;
  public:
     slink() : head(0), tail(0) {
    }

    ~slink() {
    clear();
    }
    void push_back(const T &datum) {
    node *p = new node;
    p->datum = datum;
    p->next = 0;
    if (!tail)      
        head = p;
    else
        tail->next = p;
    tail = p;
    }

template <typename Tfirst, typename Tsecond>
class Smaph {

    public:
        Smaph();
        ~Smaph();
        Smaph(const Tfirst a, const Tsecond b) {
            std::pair<Tfirst, Tsecond> pair1(a, b);
            s.push_back(pair1);
        }
    private:

        slink<std::pair<Tfirst, Tsecond> > s();


};

And finally, my main to test my program. All I want to do right now is add these two numbers to my singly linked list through my Smaph.

int main() {
        Smaph<int, double> s(3, 6.3);
}
user1299379
  • 381
  • 2
  • 4
  • 13

2 Answers2

3
slink<std::pair<Tfirst, Tsecond> > s();

This is a declaration of a function called s that takes no arguments and returns a slink<std::pair<Tfirst, Tsecond> >. When the compiler sees you do s.push_back(pair1);, it wonders what you're trying to do to that poor function. Remove the () to make it a data member:

slink<std::pair<Tfirst, Tsecond> > s;
Joseph Mansfield
  • 108,238
  • 20
  • 242
  • 324
1

On this line you did:

slink<std::pair<Tfirst, Tsecond> > s();

This is declaring a function named s that returns slink<std::pair<Tfirst, Tsecond> >. But then you did this inside one of your member functions:

s.push_back(pair1);

That isn't right, which is why your compiler alerts you of invalid use of this member function.

To fix, remove the parameters:

slink<std::pair<Tfirst, Tsecond> > s;
David G
  • 94,763
  • 41
  • 167
  • 253