我需要用glm::vec2 2来使用std::map,所以我尝试实现'<‘操作符,但是它失败了。( std::map需要这个操作员)
下面是我的测试示例中的代码:
bool operator <(const glm::vec2& l, const glm::vec2& r)
{
int lsize = l.x + l.y;
int rsize = r.x + r.y;
return lsize < rsize;
}
class A
{
public:
A()
{
test[glm::vec2(5, 5)] = 4;
}
private:
std::map<glm::vec2, int> test;
};
int _tmain(int argc, _TCHAR* argv[])
{
A a;
return 0;
}当我创建自己的Vector2类并以相同的方式在那里实现操作符时,它会编译,但是它在glm::vec2 2中失败了(我有19个错误告诉操作符'<‘不是为glm::vec2 2定义的,等等)。
error C2676: binary '<' : 'const glm::vec2' does not define this operator or a conversion to a type acceptable to the predefined operator 注意,我的操作符重载函数编译了,错误来自于使用std::map,似乎“<”glm::vec2操作符仍然被认为是未定义的。
这是GLM的源代码,如果它可以帮助您:https://github.com/g-truc/glm/tree/master/glm
发布于 2015-03-22 18:40:48
我担心你一开始就想这么做,因为我认为这可能不是你真正想要做的。但是,如果您确实想要这样做,则需要将其放在正确的命名空间中。
namespace glm {
namespace detail {
// But don't do this! This is not a good idea...
bool operator <(const glm::vec2& l, const glm::vec2& r)
{
int lsize = l.x + l.y;
int rsize = r.x + r.y;
return lsize < rsize;
}
}
}但是等等!这是不对的!
vec2不是有序的,所以实现<在数学上没有任何意义vec2没有被命令,所以你不应该把它们放在std::map里std::map在其内部保持元素的有序性。那么,当你这么做的时候会发生什么?
int main(int argc, char* argv[])
{
std::map<glm::vec2, int> m;
m[glm::vec2(1, 1)] = 10;
std::cout << m[glm::vec2(0, 2)] << '\n';
return 0;
}是的,即使我们从未在地图中添加(0,2),它也会打印出10。
您可能希望使用空间索引(例如,四叉树),或者至少使用字典顺序。否则,如果这是您实际需要的行为,则应该通过模板参数更改std::map上的比较器。
struct vec2_cmp {
bool operator()(const glm::vec2 &x, const glm::vec2 &y) { ... }
}
std::map<glm::vec2, int, vec2_cmp> m;https://stackoverflow.com/questions/29198077
复制相似问题