【发布时间】:2015-08-24 14:23:36
【问题描述】:
我有一个模板class Timer
template<typename Clock, typename Duration>
class Timer
{
public:
void Register(const std::function<void(const std::chrono::time_point<Clock> &timePoint)> &eventHandler);
private:
std::vector<std::function<void(const std::chrono::time_point<Clock> &timePoint)>> eventHandlers;
// Some more stuff.
};
现在我想在Register 中找到重复的条目,这就是问题所在。
我使用std::find 和一个简单的for 循环尝试了不同的方法。
到目前为止我能做到的最好的(删除命名空间以提高可读性):
typename vector<function<void(const time_point<Clock> &timePoint)>>::iterator it;
for(it = eventHandlers.begin(); it != eventHandlers.end(); ++it)
{
}
我的问题是将Register的参数与it进行比较。
我尝试了几件事:
typename function<void(const time_point<Clock> &timePoint)> &f = &(*it);
if(f == eventHandler)
{
// Duplicate
}
...以及其他一些更复杂的方法,但没有一个奏效。
我在解决这个问题时遇到了一些麻烦,因为我通常使用 C# 编写代码,因此我不习惯使用 C++ 进行模板化。
我该如何解决这个问题,还有更优雅的解决方案吗?
编辑:
我通常会收到此错误:
binary '==': no operator found which takes a left-hand operand of type 'std::function<void (const std::chrono::time_point<std::chrono::system_clock,std::chrono::system_clock::duration> &)>' (or there is no acceptable conversion)
【问题讨论】:
-
这里的问题不在于模板,而在于
std::functions 是not equality comparable。传递给Timer::Register的两件事相等是什么意思?