显式指定位于模板参数包之后的默认模板参数

Explicitly specify defaulted template parameter located after template parameter pack

本文关键字:参数 之后 默认 定位 于模板 包之后      更新时间:2023-10-16

为什么在以下情况下我不能显式指定d

#include <iostream>
template< typename a, typename b = int, typename ...c, typename d = int >
int
f(a, b, c..., d)
{
    return sizeof...(c);
}
int
main()
{
    std::cout << f< int, int, int, int/*, char*/ >(1, 2, 3, 4, 'd') << std::endl;
    return 0;
}

如果我取消注释最后一个模板参数,那么我期望输出2,但我得到了一个硬错误:

main.cpp:14:18: error: no matching function for call to 'f'
    std::cout << f< int, int, int, int, char >(1, 2, 3, 4, 'd') << std::endl;
             ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~
main.cpp:6:1: note: candidate function not viable: requires 6 arguments, but 5 were provided
f(a, b, c..., d)
^
1 error generated.

在这种情况下,否认它的规则是什么?

因为包是贪婪的。因此,char实际上是c的一部分,您需要提供与d相关的参数,由于默认情况,该参数的类型为int