【问题标题】:could not deduce template argument无法推断模板参数
【发布时间】:2013-02-18 17:02:40
【问题描述】:

我正在实现的部分类如下所示:

    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'

有什么建议吗?

【问题讨论】:

  • 报错信息与代码无关。上面的代码编译得很好。使用std::string 查找一些代码。还要查看编译器提供的行号。
  • @OlafDietsche 它只会编译,因为地图没有元素。一旦你尝试添加一个,它就会失败,原因很简单,Cord 没有operator&lt;
  • @juanchopanza 你是对的,但这并不能使错误消息适合代码。

标签: c++ map comparison key


【解决方案1】:

您的operator() 应该是operator&lt;

    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&lt;std::map 用来排序其密钥的。

【讨论】:

  • 显然 OP 也有一个 std::stringCord 之间的比较,从错误消息的外观来看
【解决方案2】:

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

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

【讨论】:

    【解决方案3】:

    您可以通过提供operator&lt;(const Cord&amp;, const Cord&amp;) 来解决此问题:

    // uses your operator()
    bool operator<(const Cord& lhs, const Cord& rhs) { return lhs(rhs);)
    

    或将operator()(const Cord&amp; cord) const 重命名为operator&lt;(const Cord&amp; cord) const

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-03-22
      • 2020-07-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多