I've some problem in my code I cannot deal with:
#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);
}
Compiler gives me following error in line m[b]=0; :
instanti开发者_运维知识库ated from 'void TestClass::testMethod(T, std::map) [with T = SomeClass]
Could you help find the problem??
Thanks in advance
Not even seeing the error, I can tell you one thing that you probably are doing wrong. Here:
void TestClass<T>::testMethod(T b,std::map<T,int> m){
You are aware, that you're taking a whole map by value?
That however, is not the source of the error. Map is a sorted associative container, and expects keys that can be sorted. Built in types have their sorting via the <
operator. For your own class, you need to either provide an operator, or initialize the map with a custom sorting functor.
Hence either an operator:
bool operator<(const SomeClass&,const SomeClass&)
{
return ...;
}
...or a functor:
struct CompareSomeClass {
bool operator()(const SomeClass&,const SomeClass&)
{
return ...;
}
};
This
#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);
}
compiles just fine for me using VC10 and Comeau.
Most likely, SomeClass
does not have operator<
defined for it. Define that and you should be good to go:
bool operator<(const SomeClass &sc1, const SomeClass sc2)
{
...
}
You're right. Overloading operator < in SomeClass solved problem:
bool operator<(const SomeClass &s1) const{
....
}
Thanks a lot!
精彩评论