C ++标准中的矛盾? [英] Contradiction in C++ standard?

查看:96
本文介绍了C ++标准中的矛盾?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

A std :: map 必须符合第23.1.2 / 2段中指定的关联容器的要求:

A std::map must satisfy the requirements of an associative container specified in paragraph 23.1.2/2:


每个关联容器是
参数化的Key和一个排序
关系比较导致严格
弱排序(25.3)元素
键。此外,map和multimap
将任意类型T与
Key相关联。类型Compare的对象是
,称为
容器的比较对象。这个比较对象可以是
指向函数的指针,或者是具有适当函数
调用操作符的类型的对象

Each associative container is parameterized on Key and an ordering relation Compare that induces a strict weak ordering (25.3) on elements of Key. In addition, map and multimap associate an arbitrary type T with the Key. The object of type Compare is called the comparison object of a container. This comparison object may be a pointer to function or an object of a type with an appropriate function call operator.

但是在第23.3.1 / 2中, std :: map 模板被指定为:

But then in paragraph 23.3.1/2 the std::map template is specified as:

template <class Key, class T, class Compare = less<Key>,
          class Allocator = allocator<pair<const Key, T> > >
class map;

这似乎明确禁止使用函数指针 Compare 。这是一个矛盾还是我不能正确地理解标准?

which seems to explicitly prohibit the use of a function pointer as Compare. Is this a contradiction or am I not understanding the standard correctly?

编辑:是的,我真的有的问题是为什么像GMan示例:

Yes, the problem I was really having was why code like GMan's example:

struct foo
{
    int x;
};

bool compare_foo(const foo& x, const foo& y)
{
    return x.x < y.x;
}

std::map<foo, bool, compare_foo> fooMap;

无法编译(是的,我愚蠢地混淆了比较参数)。

wouldn't compile (yeah, I stupidly mixed up the type and value of the Compare parameter).

推荐答案

比较比较器的类型。它被声明为 class 而不是 typename 没有什么区别,你可以有一个指针函数作为类型,并在地图构造函数中提供您的函数。

Compare is the type of the comparator. The fact that it is declared with class instead of typename doesn't make a difference, you can have a pointer to function as type and give your function in the map constructor.

#include <map>

bool myCmp(int a, int b) {
    return a < b;
}

void foo()
{
    std::map<int, char*, bool (*)(int, int)> m(myCmp);
}

这篇关于C ++标准中的矛盾?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆