繁体   English   中英

没有合适的用户定义转换<class>到多图</class>

[英]No suitable user-defined conversion from <class> to multimap

我是 C++ 的新手。 我试图创建一个类似于multimap的 class ,称为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<std::string, std::string>”到“std::multimap<std::string, std::string, string_size_less, std::allocator<std::pair< const std::string, std::string>>>" 存在

想要的工作分配操作员:

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++ 中重载目标类型的分配。 使用的语法甚至并不意味着(它仍在分配给multimap_viewer )。

正如评论所说,你能做的最好的事情就是编写一个转换 function。 如果可以的话,也要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;
  }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM