这段代码编译失败
template<unsigned n>
void test(char const (*)[n + 1]) { }
int main()
{
char const arr[] = "Hi";
test(&arr);
}
与误差
note: candidate template ignored: couldn't infer template argument 'n'
但是,如果您将n + 1
更改为n
,它可以正常编译。
为什么编译器不能推断出n
时,它有一个偏移添加到它?
From cppreference, in "Non-deduced contexts"部分:
在以下情况下,类型、模板和非类型值是用来组成P不参与模板参数的吗,而是使用两者之一的模板参数从别处推导出来的或明确指定的。如果模板参数为仅在非推导的上下文中使用且未明确指定,模板实参推导失败。
(…)
- 一个非类型模板参数或一个数组子表达式引用模板参数:
template<std::size_t N> void f(std::array<int, 2 * N> a);
std::array<int, 10> a;
f(a); // P = std::array<int, 2 * N>, A = std::array<int, 10>:
// 2 * N is non-deduced context, N cannot be deduced
// note: f(std::array<int, N> a) would be able to deduce N
(……)在任何情况下,如果类型名的任何部分不是推导出来的,那么整个类型名就是非推导出来的上下文。(…)
由于n + 1
是子表达式,因此不能推导出整个上下文。