【问题标题】:Partial template deduction in constructors构造函数中的部分模板推导
【发布时间】:2021-02-12 00:25:02
【问题描述】:

问题:我经常遇到这样的情况,有些类型可以从构造函数的参数中推断出来,但不是全部:

template <typename Res, typename Arg>
struct adder {
    adder (Arg a1, Arg a2) : a1 {a1}, a2 {a2} {}
    void compute () { res = a1 + a2; }
    Res result () { return res; }

    Arg a1, a2;
    Res res;
};

如果我使用int 参数并想指定unsigned 作为结果类型,我想写如下内容:

auto add = adder<unsigned>(42, -51);

……这行不通。不过,我不想明确提及int。

候选解决方案:我可以想到两种“让它发挥作用”的方法,首先是与制造商合作:

template <typename Res>
struct wrapper {
    template <typename Arg>
    static auto make_adder (Arg a1, Arg a2) {
      return adder<Res, Arg> (a1, a2);
    }
};

auto add = wrapper<unsigned>::make_adder (42, -51);

其次,确保所有类型都可以在构造函数中推导出来:

template <typename Res, typename Arg>
struct adder_extra {
    adder_extra (Arg a1, Arg a2, Res r) : a1 {a1}, a2 {a2} {}
    void compute () { res = a1 + a2; }
    Res result () { return res; }

    Arg a1, a2;
    Res res;
};

auto add = adder_extra (42, -51, (unsigned) 0);

问题:有首选方法吗?这可以用另一种方式更巧妙地解决吗?

【问题讨论】:

  • 您可以将 tag 传递为 std::type_identity&lt;T&gt;(或 std::in_place_type_t&lt;T&gt; 或您的),而不是第二个 sn-p 中的虚拟 Res。

标签: c++ templates constructor c++17


【解决方案1】:

你没有提到的一个选项是像标准库那样做1,并释放 maker 函数:

template <typename Res, typename Arg>
auto make_adder (Arg a1, Arg a2) {
      return adder<Res, Arg> (a1, a2);
}

函数的模板参数推导允许指定模板参数的一部分。 make_adder&lt;unsigned&gt;(42, -51) 完全有效,可以追溯到 C++98。

这也是一种解决方法,没错。但这是一种流行且惯用的说法。


1 - std::make_unique、std::make_shared、std::make_optional、std::make_any、std::make_tuple等

【讨论】:

  • 啊,太棒了!我相信我的问题确实是“什么是惯用的”,所以我们就是这样。将等待其他人加入,但这似乎应该是正确的答案。仅仅为了绕过语法限制而使用 make 函数仍然感觉不自然,但这比我建议的要好!
猜你喜欢
  • 2023-03-09
  • 2011-10-21
  • 1970-01-01
  • 2019-06-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多