【问题标题】:What's the point of having a constructor with a default argument that takes a user-defined type?使用带有用户定义类型的默认参数的构造函数有什么意义?
【发布时间】:2022-01-03 19:39:30
【问题描述】:

好的,我正在尝试从 STL 重新实现 Vector 类。这是模板类的一小部分,其中包括作为参数传递的分配器的简单 typedef。

template<typename T, typename Allocator = std::allocator<T>>
class vector {
public:
    typedef Allocator                                   allocator_type;
    // Other typedefs...
}

很简单,但是,我就是无法理解这个构造函数:

explicit vector(const allocator_type &alloc = allocator_type());

allocator_type() 指的是什么?是typedef吗?这是某种函数调用吗?甚至可以在这里传递用户定义的类型吗?我可能只是错过了一些东西。

【问题讨论】:

  • 指的是allocator_type的默认构造函数。 vector 需要一个对分配器实例的 const 引用。如果没有给出默认值allocator_type(),则使用它提供默认构造的分配器实例。 (由于唯一参数的默认值,vector 的这个构造函数也提供了vector 的默认构造函数。)
  • @Simonechebelnome 有没有回答您的问题?

标签: c++ oop templates stl


【解决方案1】:

是的,是typedef

类模板参数Allocator 有一个默认类型std::allocator&lt;T&gt;。是否使用它并不重要。重要的是无论Allocator 是什么类型,它都会获得allocator_type 形式的类型别名。

构造函数有一个默认值,即默认构造的allocator_type(无论是什么类型)。您可以向构造函数提供allocator_type 的实例(可能不是默认构造的),它会使用它。

【讨论】:

    【解决方案2】:

    allocator_typeAllocator 的别名。 它们的含义相同,但 Allocator 仅对类成员可见,因此需要别名才能使其成为 public

    您找到的构造函数相当于:

    explicit vector(const Allocator &alloc = Allocator());
    

    除了这个符号对类的用户来说更容易混淆,他们只能在他们的代码中使用名称allocator_type

    = allocator_type() 只是告诉编译器它是一个可选参数。如果用户不向vector 的构造函数提供任何其他allocator_type 对象,则将使用Allocator/allocator_type 的默认构造函数来创建要传递的对象。

    【讨论】:

      【解决方案3】:

      回答基本问题:这个构造函数的意义何在?这是一种特殊的默认构造函数。 SFINAE(替代失败不是错误)意味着当Allocator 不是默认构造时,这不是vector 的默认构造函数。不过,它仍然可以用作普通的构造函数。

      【讨论】:

        猜你喜欢
        • 2018-07-17
        • 1970-01-01
        • 2016-02-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-10-17
        • 1970-01-01
        • 2022-11-05
        相关资源
        最近更新 更多