[英]C++ templates error: instantiated from 'void TestClass::testMethod(T, std::map) [with T = SomeClass]
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; 编译器在行m [b] = 0中给了我以下错误; :
:
instantiated from 'void TestClass::testMethod(T, std::map) [with T = SomeClass] 从'void TestClass :: testMethod(T,std :: map)实例化[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.
Map是一个排序的关联容器,并且期望可以排序的键。 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. 使用VC10和Comeau编译对我来说很好。
Most likely, SomeClass
does not have operator<
defined for it. 最有可能的是,
SomeClass
没有为其定义operator<
。 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:
SomeClass中的重载运算符<解决了问题:
bool operator<(const SomeClass &s1) const{
....
}
Thanks a lot! 非常感谢!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.