4

从上一个问题的已接受答案中,我发现了一条我不知道的关于模板和格式良好的规则

该程序格式错误,不需要诊断,如果:

  • [...]
  • 可变参数模板的每个有效特化都需要一个空模板参数包,或者
  • [...]

根据这条规则(如果我理解正确的话),下面的模板函数格式不正确

template <typename ... Ts>
int foo (std::tuple<Ts...> const &)
 { return std::get<sizeof...(Ts)>(std::tuple<int>{42}); }

因为唯一有效的特化需要和空Ts...参数包。

但是(可能是因为我不太懂英语)如果模板有两个或更多参数包,我不确定是否理解这个规则。

我的意思是......以下foo()功能

#include <tuple>
#include <iostream>

template <typename ... Ts, typename ... Us>
int foo (std::tuple<Ts...> const &, std::tuple<Us...> const &)
 { return std::get<sizeof...(Ts)+sizeof...(Us)-1U>(std::tuple<int>{42}); }

int main ()
 {
   auto t0 = std::tuple<>{};
   auto t1 = std::tuple<int>{0};

   //std::cout << foo(t0, t0) << std::endl; // compilation error
   std::cout << foo(t0, t1) << std::endl;   // print 42
   std::cout << foo(t1, t0) << std::endl;   // print 42
   //std::cout << foo(t1, t1) << std::endl; // compilation error
 }

是良构还是良构?

因为它的有效特化要求Ts... or Us...为空(并且其他参数包的大小正好为 1)。

如果有一个必须为空的空参数包(因此我的示例应该是格式正确的,因为两个参数包都不能为空),则该规则应该被解释为程序格式错误,或者在某种意义上是如果在每个专业中至少有一个空参数包,则格式不正确,不一定在每个专业中都相同(所以我的示例应该是格式错误的)?

4

0 回答 0