mskoryk
mskoryk

Reputation: 506

request for a memeber of template class

I have a template class with two template arguments with the following constructor and member:

template <class T, class TCompare>
class MyClass {
...
public:
MyClass(TCompare compare);
void addElement(T newElement);
...
};

And I have a structure which overloads operator () for integer comparison:

struct IntegerLess {
    bool operator () {const int& a, const int& b) {
       if (a < b)
           return true;
       return false;
    }
};

I create an object of class 'MyClass' and try to use it:

MyClass<int, IntegerLess> myClassObject(IntegerLess());
myClassObject.addElement(10);

However, I got the following compile-time error:

error: request for member ‘addElement’ in ‘myClassObject’, which is of non-class type ‘MyClass<int, IntegerLess>(IntegerLess (*)())’

How can I correct it? Thanks!

Upvotes: 3

Views: 56

Answers (2)

lethal-guitar
lethal-guitar

Reputation: 4519

Declare the IntegerLess object separately:

IntegerLess comparator;
MyClass<int, IntegerLess> myClassObject(comparator);
myClassObject.addElement(10);

Alternatively, add parentheses like juanchopanza suggested.

Upvotes: 1

juanchopanza
juanchopanza

Reputation: 227418

This is the most vexing parse. You can fix the problem by throwing in an extra set of parentheses:

MyClass<int, IntegerLess> myClassObject((IntegerLess()));
//                                      ^             ^

Note that if you had passed an lvalue directly, there would have been no scope for this parse:

IntegerLess x;
MyClass<int, IntegerLess> myClassObject(x);

Upvotes: 3

Related Questions