[英]C++ function template overload resolution with nested types
Why does overload resolution fail in this case?为什么在这种情况下重载解析会失败? I would have expected that
foo<int>
could be deduced.我本来期望可以推断出
foo<int>
。
template <typename T> struct Templ { typedef T Type; };
template <typename T> void foo(typename Templ<T>::Type) {}
foo(1); //error can't deduce template argument for T
The rules of C++ say that's not a deduced context. C++ 的规则说这不是推断的上下文。 If one thinks about why that might be, there are a few things that comes to mind.
如果有人考虑为什么会这样,就会想到一些事情。
Deduction in this case is asking the compiler to invert a type-level function.在这种情况下,推论是要求编译器反转类型级别的 function。 That may be ambiguous or impossible.
这可能是模棱两可的或不可能的。 That requires introducing rules around specialization visibility.
这需要引入有关专业化可见性的规则。 And such a function may be complex even when the solution is unambiguous:
即使解决方案明确,这样的 function 也可能很复杂:
template <std::uint32_t>
struct foo;
template <>
struct foo<0u> {
using type = std::integral_constant<int, 1>;
};
template <>
struct foo<1u> {
using type = std::integral_constant<int, 2>;
};
template <std::uint32_t N>
struct foo {
using type = std::integral_constant<int,
foo<N-1>::type::value + foo<N-2>::type::value
>;
};
template <std::uint32_t N>
void using_foo(typename foo<N>::type);
// would deduce N=20u
using_foo(std::integral_constant<int, 17711>{});
Additionally, it seems like deduction in such cases would introduce ODR hazards.此外,在这种情况下,扣除似乎会引入 ODR 危害。 By calling a function, with some arbitrary parameter, we would be deducing a parameter type through an unrelated type-function, and we require that the relevant specializations of that type-function be visible, which isn't something that's obvious at all at the call site.
通过使用任意参数调用 function,我们将通过不相关的类型函数推导出参数类型,并且我们要求该类型函数的相关特化是可见的,这根本不是显而易见的呼叫站点。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.