簡體   English   中英

C ++模板錯誤:從'void TestClass :: testMethod(T,std :: map)實例化[T = SomeClass]

[英]C++ templates error: instantiated from 'void TestClass::testMethod(T, std::map) [with T = SomeClass]

我的代碼中有一些我無法處理的問題:

#ifndef TESTCLASS_H_
#define TESTCLASS_H_

#include <map>

using namespace std;
template <typename T>
class TestClass
{
public:
  TestClass(){};
  virtual ~TestClass(){};
  void testMethod(T b,std::map<T,int> m);
};

template <typename T>
void TestClass<T>::testMethod(T b,std::map<T,int> m){
  m[b]=0;
}
#endif /*TESTCLASS_H_*/

int main(int argc, char* argv[]) {
  SomeClass s;
  TestClass<SomeClass> t;
  map<SomeClass,int> m;
  t.testMethod(s,m);
}  

編譯器在行m [b] = 0中給了我以下錯誤;

從'void TestClass :: testMethod(T,std :: map)實例化[T = SomeClass]

你能幫忙找到問題嗎?

提前致謝

甚至沒有看到錯誤,我可以告訴您一件事,您可能做錯了。 這里:

void TestClass<T>::testMethod(T b,std::map<T,int> m){

您是否知道,您正在按價值繪制整個地圖?

但是,這並不是錯誤的根源。 Map是一個排序的關聯容器,並且期望可以排序的鍵。 內置類型通過<運算符對其進行排序。 對於您自己的類,您需要提供一個運算符,或者使用一個自定義的排序函子來初始化地圖。

因此,任何一個運算符:

bool operator<(const SomeClass&,const SomeClass&)
{ 
     return ...;
} 

...或函子:

struct CompareSomeClass {
  bool operator()(const SomeClass&,const SomeClass&) 
  {
      return ...;
  }
};

這個

#include <map>

class SomeClass {};

bool operator<(const SomeClass&,const SomeClass&);

class in {};

template <typename T>
class TestClass
{
public:
  TestClass(){};
  virtual ~TestClass(){};
  void testMethod(T b,std::map<T,int> m);
};

template <typename T>
void TestClass<T>::testMethod(T b,std::map<T,int> m){
  m[b]=0;
}

int main() {
  SomeClass s;
  TestClass<SomeClass> t;
  std::map<SomeClass,int> m;
  t.testMethod(s,m);
}

使用VC10和Comeau編譯對我來說很好。

最有可能的是, SomeClass沒有為其定義operator< 定義那個,你應該很好:

bool operator<(const SomeClass &sc1, const SomeClass sc2)
{
    ...
}

你是對的。 SomeClass中的重載運算符<解決了問題:

bool operator<(const SomeClass &s1) const{
    ....
 }

非常感謝!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM