【问题标题】:Additional type in template deduction guide模板扣除指南中的附加类型
【发布时间】:2020-02-17 21:44:07
【问题描述】:

这个 sn-p 演示了如何使用推导指南来允许 source_location::current 与参数包一起使用(参见 https://stackoverflow.com/a/57548488/1421332):

template <typename... Params>
struct Test
{
   Test(Params&&... params,
        const std::source_location& loc = std::source_location::current());
};

template <typename ...Params>
Test(Params&&...) -> Test<Params...>;

这样使用:

Test(5, 'A', 3.14f, "foo");

现在我想通过一个额外的类型 T 来扩展 struct Test ,它应该明确指定。我尝试了以下但不接受扣除指南:

template <typename T, typename... Params>
struct Test
{
    Test(Params&&... params,
         const std::source_location& loc = std::source_location::current());
};

template <typename T, typename ...Params>
Test(Params&&...) -> Test<T, Params...>;

编译器说:

推导模板包含模板参数,不能 推断出来的。

我需要额外的 T 来允许 struct Test 在内部构建用户指定类型的对象。

应该这样使用:

Test<MyType>(5, 'A', 3.14f, "foo");

是否可以定义包含附加T的扣除指南?

【问题讨论】:

    标签: c++ c++17 template-argument-deduction


    【解决方案1】:

    你不能用这种语法来做:

    Test<MyType>(5, 'A', 3.14f, "foo");
    

    因为没有“部分”类模板参数推导之类的东西。全有或全无 - 您可以指定 all 类模板参数或 none 类模板参数。

    但是,您可以将类型移到上方:

    template <typename T> struct type_t {};
    template <typename T> inline type_t<T> type{};
    
    Test(type<MyType>, 5, 'A', 3.14f, "foo");
    

    现在你推断出了类型。您甚至可以编写演绎指南来要求这种用法:

    template <typename T, typename ...Params>
    Test(type_t<T>, Params&&...) -> Test<T, Params...>;
    

    虽然Test 的构造函数仍然需要先接受type_t&lt;T&gt; 参数。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-02-19
      • 2012-10-30
      • 1970-01-01
      • 2020-11-30
      • 1970-01-01
      • 2019-09-23
      • 2015-12-09
      相关资源
      最近更新 更多