【问题标题】:c++ operator overloading in template classc ++模板类中的运算符重载
【发布时间】: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


【解决方案1】:

那是因为你没有在比较你认为你在比较的东西:

if(event1 < event2) {

event1event2 都具有 Event&lt;int&gt;* 类型。指针有一个内置的operator&lt;,它做的事情与你想做的事情完全无关。如果要比较指向的实际 Event&lt;int&gt;s,则必须取消引用它们:

if (*event1 < *event2) {

这时你会遇到templates can only be implemented in the header file的问题。

【讨论】:

  • 哦。谢谢你。我为我的priority_queue 做了比较重载。我该怎么做? std::priority_queue&lt;Event&lt;T&gt;*, std::vector&lt;Event&lt;T&gt;*&gt;&gt; q;
  • @alexander-fire 提示:priority_queue 采用三个模板参数。
  • 我知道,但我还有另一个问题。 (请参阅已编辑的问题。)
  • @alexander-fire 请不要将问题更新为新问题 - 它会使现有答案无效。我回滚了你的编辑。
猜你喜欢
  • 1970-01-01
  • 2016-06-21
  • 1970-01-01
  • 2012-11-14
  • 2016-06-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多