请求模板类的成员

时间:2013-10-31 10:20:36

标签: c++ class templates

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

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

我有一个结构,它重载operator()进行整数比较:

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 (*)())’

我该如何纠正?谢谢!

2 个答案:

答案 0 :(得分:3)

这是the most vexing parse。您可以通过抛出一组额外的括号来解决问题:

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

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

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

答案 1 :(得分:1)

单独声明IntegerLess对象:

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

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