簡體   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