【发布时间】:2016-03-09 18:04:23
【问题描述】:
我开发了一个模板类。 现在我想重载低于运算符。 我正常尝试过,就像普通班级一样,但它不起作用。
事件.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;
}
程序打印“event1 is lowert”。 但是如果我的重载函数可以工作,“event2 会更大” (我比较了 event1 中的时间 5 和 event 2 中的时间 4)
【问题讨论】:
-
模板类函数以及为其重载的运算符必须在 .h 文件中定义。
-
这甚至不应该编译。
-
@SergeyA,我在头文件`bool operator
-
@NathanOliver,它使用链接器解决方法
TemporaryFunction进行编译 -
@alexander-fire 你是怎么做到provide the template implementation in a translation unit的?
标签: c++ templates operator-overloading template-classes