无法推断模板参数

could not deduce template argument

本文关键字:参数      更新时间:2023-10-16

我要实现的类的一部分是这样的:

    struct Cord
    {
        int x_cord;
        int y_cord;
        Cord(int x = 0,int y = 0):x_cord(x),y_cord(y) {}
        bool operator()(const Cord& cord) const
        {
            if (x_cord == cord.x_cord)
            {
                return y_cord < cord.y_cord;
            }
            return x_cord < cord.x_cord;
        }
    };
class Cell
    {
    };
std::map<Cord,Cell> m_layout;

我无法编译上面得到

的代码
error C2784: 'bool std::operator <(const std::basic_string<_Elem,_Traits,_Alloc> &,const _Elem *)' : could not deduce template argument for 'const std::basic_string<_Elem,_Traits,_Alloc> &' from 'const Layout::Cord'

有什么建议吗?

您的operator()应该是operator<:

    bool operator<(const Cord& cord) const
    {
        if (x_cord == cord.x_cord)
        {
            return y_cord < cord.y_cord;
        }
        return x_cord < cord.x_cord;
    }

operator<std::map用来排序键的。

您可以通过提供operator<(const Cord&, const Cord&):

来解决这个问题
// uses your operator()
bool operator<(const Cord& lhs, const Cord& rhs) { return lhs(rhs);)

或将operator()(const Cord& cord) const重命名为operator<(const Cord& cord) const

你在map中使用你的类,它需要为它定义operator<

// ...
bool operator<(const Cord& cord) const
{
  if (x_cord == cord.x_cord)
    return y_cord < cord.y_cord;
  return x_cord < cord.x_cord;
}
// ...