mskoryk
mskoryk

Reputation: 506

explicit initializtion of template class

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

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

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 want to pass this structure as an argument to MyClass constructor. I have tried the following:

MyClass<int> myClassObject(IntegerLess());

and

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

However, both times I have a compile-time error. In the first case

error: wrong number of template arguments (1, should be 2)

and in the second case

error: template argument 2 is invalid

Can someone point out what is the right option here? Thanks!

Upvotes: 1

Views: 65

Answers (1)

Number 1 is wrong because class template arguments cannot be deduced - you must specify them explicitly (unless they have default values in the class template definition).

Number 2 just has an extra typename which shouldn't be there. The correct syntax is:

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

And in case IntegerLess is your actual code and not a mock you produced to simplify the question, consider using std::less<int> instead, which does precisely what your class does. You could even make that a default template argument for the class, like this:

template > class MyClass { public: explicit MyClass(TCompare compare = TCompare()); // ... the rest as before };

If you do that, you will then be able to use it in simplified form:

MyClass<int> myClassObject;

Upvotes: 2

Related Questions