gpt4 book ai didi

c++ - std::set 构造函数签名混淆

转载 作者:太空狗 更新时间:2023-10-29 20:51:12 29 4
gpt4 key购买 nike

我正在阅读关于如何定义 setC++ Primer .当我查看关于 setcppreference 时,我对 set 的类和构造函数签名感到困惑.

来自正文:

bool compareIsbn(){....}
multiset<Sales_data, decltype(compareIsbn) *> bookstore(compareIsbn)

文本 1:

To use our own operation, we must define the multiset with two types: the key type, Sales_data, and the comparison type, which is a function pointer type that can point to compareIsbn. When we define objects of this type, we supply a pointer to the operation we intend to use. In this case, we supply a pointer to compareIsbn:

所以从 text1 看来,我需要在 set<Class A, a function pointer> 中放置一个函数指针 .

但是当我查找cppreference ,“签名”(不确定是否正确)是:

template<
class Key,
class Compare = std::less<Key>,
class Allocator = std::allocator<Key>
> class set;

问题1:所以第二个参数应该是class


文本 2:

We can write compareIsbn instead of &compareIsbn as the constructor argument because when we use the name of a function, it is automatically converted into a pointer if needed. We could have written &compareIsbn with the same effect.

同样来自 cppreference constructor of set (我觉得教科书上用的是第一个构造函数):

set();
explicit set( const Compare& comp,
const Allocator& alloc = Allocator() );

问题 2:构造函数不需要函数引用吗?它从哪里说它需要一个函数指针


需要一些帮助来理解“签名”,提前致谢:D。

附言:

  1. 教科书使用multiset作为一个例子,但是 set 的“签名”和 multiset非常相似。
  2. 我不知道是什么const Allocator& alloc = Allocator()意思是,但我想也许这是自动完成的事情?我现在可能会忽略它。

最佳答案

这有点困惑,但很接近正确。

用“类”指定的类型模板参数是一个历史/语法怪癖;这实际上表明参数是一种类型。 'typename' 也是合法的并且在语义上是相同的:

template<typename T>
struct Foo {
T thing;
}

template<class T>
struct Bar {
T thing;
}

// Foo and Bar will work identically

在本书的示例中,传递给模板的类型是“指向 CompareIsbn 类型的指针”


关于你的第二个问题,记住Compare是一种类型:

template<typename T>
void Foo(const T& object) { ... }

模板函数 Foo 期望传递一个对 T 的 const 引用。如果 T 是一个指针类型,那么它期望一个对指针的 const 引用:

Thing* bar = new Thing();
Foo<Thing*>(bar); // This instantiation of the template has signature void (const Thing*&)

在书中的示例中,Comparedecltype(CompareIsbn)* , 所以你必须通过 const decltype(CompareIsbn)*&给构造函数。


cppreference 有一个 page详细说明用于 Compare 的类型的要求set 中的参数模板,您可能会发现它很有用。简短的版本是它必须是这样的代码才能工作的类型:

// Given Compare comp
// Given Key a, b
bool b = comp(a, b);

关于如何调用 operator() 有一些要求必须守规矩。

函数指针将在该上下文中工作,所以没问题。但也是std::function ,或任何实现 operator() 的类型以正确的行为。 = std::less<Key>模板声明中的位正在为 Compare 设置默认值参数是这样一个对象,它只是尝试使用 Key::operator< .

Allocator parameter 也是一个类似函数的对象,用于创建新的 Key必要时的对象。您很少需要提供显式分配器;默认实现在几乎所有情况下都能正常工作。

关于c++ - std::set 构造函数签名混淆,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51183688/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com