【问题标题】:No matching function for call to ‘std::less<int>::less(const int&, const int&)’没有匹配函数调用‘std::less<int>::less(const int&, const int&)’
【发布时间】:2016-01-07 20:46:31
【问题描述】:

我试着写:

#include <functional>

template<class T, class func = std::less<T>>
class Car {
public:
    void check(const T& x, const T& y) {
        func(x, y);            //.... << problem
    }
};


int main() {
    Car<int> car;
    car.check(6, 6);

    return 0;
}

我的意思是它会识别通常的&lt;int,但它会显示我标记的位置:

没有匹配函数调用‘std::less::less(const int&, const int&)'

但是,如果我使用自定义 func 创建一个 Car,那么它可以工作...我该如何解决这个问题?

【问题讨论】:

  • 编辑参数为T

标签: c++ class templates


【解决方案1】:

您的问题是您需要func 的实例,因为std::less&lt;T&gt; 是函子(即类类型)而不是函数类型。当你有

func(x, y);

您实际上尝试使用xy 作为构造函数的参数构造一个未命名的std::less&lt;T&gt;。这就是为什么你得到

没有匹配函数调用‘std::less::less(const int&, const int&)’

因为std::less::less(const int&amp;, const int&amp;) 是一个构造函数调用。

你可以看到它是这样工作的:

#include <functional>

template<class T, class func = std::less<T>>
class Car {
    func f; 
public:
    void check(const int& x, const int& y) {
        f(x, y);
        // or
        func()(x, y); // thanks to Lightness Races in Orbit http://stackoverflow.com/users/560648/lightness-races-in-orbit
    }
};


int main() {
    Car<int> car;
    car.check(6, 6);

    return 0;
}

Live Example

【讨论】:

  • 也许还澄清了它是一个类类型(即函子的类型)而不是函数类型。额外的教学z
  • IOW,请澄清“调用”func(x,y) 试图构造 std::less&lt;T&gt; 类型的对象。
  • @Stabilo 没问题。很高兴能提供帮助。
猜你喜欢
  • 2023-04-08
  • 1970-01-01
  • 1970-01-01
  • 2010-11-11
相关资源
最近更新 更多