【问题标题】:No suitable user-defined conversion from <class> to multimap没有合适的用户定义的从 <class> 到 multimap 的转换
【发布时间】:2020-12-16 22:02:25
【问题描述】:

我是 C++ 新手。我试图创建一个类似于multimap 的类,称为multimap_viewer。我希望能够将我的multimap_viewer 转换为multimap,但我只是不知道如何。我试图编写一个赋值运算符,但它不起作用。请有人指出我正确的方向吗?

演示错误的代码:

multimap_viewer<std::string, std::string> m_view;
std::map<std::string, std::string> mymap;
mymap[ "this" ] = "that";
m_view.add( mymap );

std::multimap<std::string, std::string, string_size_less> a = m_view;

我在最后一行收到的错误是:

没有合适的用户定义从“multimap_viewer<:string std::string>”到“std::multimap<:string std::string string_size_less std::allocator :pair>>>" 存在

我的想要工作分配操作员:

template <class T, class V>
class multimap_viewer
{
  public: 
  std::multimap<T, V, class Comp, std::allocator<std::pair<const T, V>>>& operator=(multimap_viewer<T, V> mv)
  {
    std::multimap<T,V, class Comp, std::allocator<std::pair<const T, V>>> mp;
    // copy items and stuff
    return *mp;
  }
}

【问题讨论】:

标签: c++ c++11


【解决方案1】:

不幸的是,在 C++ 中,您通常不能重载目标类型的赋值。 使用的语法甚至并不意味着(它仍在分配给multimap_viewer)。

正如评论所说,您能做的最好的事情就是编写一个转换函数。 如果可以的话,也可以explicit

(代码未测试)

template <class T, class V>
class multimap_viewer
{
  public: 
  /*explicit*/ operator std::multimap<T, V, class Comp, std::allocator<std::pair<const T, V>>>() const{
    std::multimap<T,V, class Comp, std::allocator<std::pair<const T, V>>> mp;
    // copy items and stuff
    return mp;
  }
}

【讨论】:

  • 将其设为 explicit 会破坏在作业中使用它的目的。
  • @Eugene 是的,但这不一定是件好事。转换仍然可以通过更明确的方式发生。例如std::multimap&lt;...&gt; a{m_view};.
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-09-01
  • 2022-01-24
  • 1970-01-01
  • 2021-02-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多