具有嵌套类型的C++函数模板重载解析



为什么在这种情况下重载解析失败?我本以为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

C++的规则说这不是一个推导的上下文。如果你想一想为什么会这样,你会想到一些事情。

在这种情况下,推导是要求编译器反转类型级函数。这可能是模棱两可或不可能的。这需要引入关于专业化可见性的规则。即使解决方案是明确的,这样的函数也可能很复杂:

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>{});

此外,在这种情况下,似乎推断会引入ODR危害。通过调用一个带有任意参数的函数,我们将通过一个不相关的类型函数来推导参数类型,并且我们要求该类型函数的相关专业化是可见的,这在调用站点上根本不是显而易见的。

最新更新