I´ve developed an template class. Now I want to overload the lower than operator. I tried it normally, like with a normal class, but it doesn´t work.
Event.h
#ifndef EVENT_H
#define EVENT_H
#include<string>
#include <functional>
template<class T>
class Event
{
public:
Event(std::string Name, std::function<T ()> fnktptr, int time, Event*resultingEvent);
virtual ~Event();
bool operator < (const Event &e) const;
std::string Name;
Event *resultingEvent;
int time;
std::function<T ()> fnktptr;
};
#endif // EVENT_H
Event.cpp
#include "Event.h"
#include<iostream>
using namespace std;
template<class T>
Event<T>::Event(std::string Name,std::function<T ()> fnktptr, int time, Event*resultingEvent) : Name(Name), fnktptr(fnktptr), time(time), resultingEvent(resultingEvent)
{
//ctor
}
template<class T>
Event<T>::~Event()
{
//dtor
}
template<class T>
bool Event<T>::operator < (const Event& e) const
{
if(this->time < e.time) {
return true;
}
else {
return false;
}
}
// No need to call this TemporaryFunction() function,
// it's just to avoid link error.
void TemporaryFunction ()
{
Event<int> TempObj("",nullptr,0,nullptr);
}
main.cpp
Event<int> *event1 = new Event<int>("sadfsf", nullptr, 5, nullptr);
Event<int> *event2 = new Event<int>("sadfsf", nullptr, 4, nullptr);
if(event1 < event2) {
cout << "event1 is lower" << endl;
}
else {
cout << "event1 is greater" << endl;
}
The program prints "event1 is lowert". But if my overloading function would work, "event2 would be greater" (I compare the time 5 in event1 with the time 4 in event 2)
That's because you're not comparing what you think you're comparing:
if(event1 < event2) {
event1
and event2
both have type Event<int>*
. Pointers have a builtin operator<
, which does something that is entirely unrelated to what it is you want to do. If you want to compare the actual Event<int>
s that are pointed to, you'll have to dereference them:
if (*event1 < *event2) {
at which point you'll run into the issue that templates can only be implemented in the header file.