尾随类模板参数未推断

时间:2017-08-06 05:30:50

标签: c++ templates gcc c++17 type-deduction

下面的代码无法使用gcc 7.1.0进行编译,gcc 7.1.0抱怨在main的第二行提供了错误数量的模板参数。此版本的GCC是supposed to implement模板参数推断类模板。

我认为编译器应该能够推导出Bar的类模板参数T2,这意味着我不应该在{Bar<int, int>的第17.8.1.3节中明确指定两个参数(template <typename T> struct Foo { Foo(T t) {} }; template <typename T1, typename T2> struct Bar { Bar(T2 t) {} }; template <typename T1, typename T2> void bar(T2 t) {} int main(int argc, char **argv) { Foo(42); // Works Bar<int>(42); // Fails to compile with "wrong number of // template arguments (1, should be 2)" bar<int>(42); // Works } ) {3}},&#34;可以推导出(17.8.2)或从默认模板参数获得的尾随模板参数可以从显式模板参数列表中省略。&#34; < / em>的

我错了吗?编译器错了吗?这是疏忽还是故意设计?

[
  {
    "EmpId": 1,
    "Name": "Abc",
    "Status": "P",
    "StatusDate": "01/01/2017"
  },
  {
    "EmpId": 1,
    "Name": "Abc",
    "Status": "A",
    "StatusDate": "01/02/2017"
  },
  {
    "EmpId": 2,
    "Name": "Xyz",
    "Status": "P",
    "StatusDate": "01/01/2017"
  },
  {
    "EmpId": 2,
    "Name": "Xyz",
    "Status": "P",
    "StatusDate": "01/02/2017"
  }
]

1 个答案:

答案 0 :(得分:18)

这是预期的行为;与template argument deduction(对于函数模板)不同,class template argument deduction(因为C ++ 17)仅在没有提供模板参数时才有效。

  

仅在没有模板时才执行类模板参数推导   提供了参数。如果指定了至少一个参数,   扣除不会发生。

std::tuple t(1, 2, 3);              // OK: deduction
std::tuple<int,int,int> t(1, 2, 3); // OK: all arguments are provided
std::tuple<int> t(1, 2, 3);         // Error: partial deduction

这意味着对于您的示例,您无法利用类模板参数推断,并且必须指定所有模板参数。如果希望类模板参数推导生效,则必须指定none,但不能推导出模板参数T1

另一方面,以下代码可以使用。

template <typename T1, typename T2>
struct Bar {
    Bar(T1, T2) {}   // make it possible to deduce T1
};

int main(int argc, char **argv) {
    Bar bar(42, 42); // take advantage of class template argument deduction
}