3

我有一个带有两个模板参数的模板类,其中包含以下构造函数和成员:

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

我有一个重载运算符 () 以进行整数比较的结构:

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

我创建了一个“MyClass”类的对象并尝试使用它:

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

但是,我收到以下编译时错误:

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

我该如何纠正?谢谢!

4

2 回答 2

3

这是最令人头疼的解析。您可以通过添加一组额外的括号来解决此问题:

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

请注意,如果您直接传递了左值,则此解析将没有范围:

IntegerLess x;
MyClass<int, IntegerLess> myClassObject(x);
于 2013-10-31T10:23:36.747 回答
1

单独声明IntegerLess对象:

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

或者,添加类似 juanchopanza 建议的括号。

于 2013-10-31T10:23:55.890 回答