代码之家  ›  专栏  ›  技术社区  ›  Peter Alexander

用free函数作为伪构造函数利用模板参数推导

  •  6
  • Peter Alexander  · 技术社区  · 14 年前

    使用自由函数作为伪构造函数以避免显式指定模板参数是一种常见的模式/习惯用法吗?

    例如,每个人都知道 std::make_pair ,它使用其参数来推断 pair 类型:

    template <class A, class B>
    std::pair<A, B> make_pair(A a, B b)
    {
      return std::pair<A, B>(a, b);
    }
    
    // This allows you to call make_pair(1, 2),
    // instead of having to type pair<int, int>(1, 2)
    // as you can't get type deduction from the constructor.
    

    stl也在大量使用这个 <functional> ( bind1st , not1 , ptr_fun

    我发现自己经常使用这个,所以我只是想知道是否有其他人使用它,是否有这个模式的名称?

    1 回复  |  直到 14 年前
        1
  •  8
  •   Johannes Schaub - litb    14 年前

    很明显它被称为“对象生成器”。见 "More C++ Idioms" "Boost" 关于这个话题。

    我个人觉得它非常有用,并且经常使用。

    另外,我认为可以将表达式模板视为对象生成器的一种特殊形式,因为它们所做的只是通过操作数类型和通常也可以手动指定的数据来构造复杂类型。但是,他们在隐式调用生成器

    a + b + c =>
      Add<Add<A, B>, C>(...)