【发布时间】:2020-04-20 15:52:20
【问题描述】:
以下程序无法编译:
template <unsigned int dim, unsigned int N, bool P, bool C, class... ParametersType>
void test(ParametersType&&... par)
{
}
int main()
{
test<2, 3, true, false>(2, 1, {8, 8});
}
错误信息
g++ -std=c++17 -O1 -Wall -pedantic -pthread main.cpp && ./a.out
main.cpp: In function 'int main()':
main.cpp:8:41: error: too many arguments to function 'void test(ParametersType&& ...)
[with unsigned int dim = 2; unsigned int N = 3; bool P = true; bool C = false; ParametersType = {}]'
8 | test<2, 3, true, false>(2, 1, {8, 8});
| ^
main.cpp:2:6: note: declared here
2 | void test(ParametersType&&... par)
| ^~~~
表示参数包ParametersType...推导为空,而我希望根据传递给test的参数类型推导它。
问题在于传递给test 的{8, 8} 参数。
将std::array 显式传递给函数可以解决问题:
#include <array>
template <unsigned int dim, unsigned int N, bool P, bool C, class... ParametersType>
void test(ParametersType&&... par)
{
}
int main()
{
test<2, 3, true, false>(2, 1, std::array<int, 2>{8, 8});
}
为什么编译器在第一个示例中显然错误地推导出包?
如果编译器无法将{8, 8} 推断为std::array,我预计会出现“无法推断”错误。为什么编译器将包推导出为空包?
【问题讨论】:
标签: c++ variadic-templates template-argument-deduction