采用以下模板结构:
template<int n, typename... Ts>
struct Widget {};
如何专注于sizeof...(Ts) == n
的情况?例如。 Widget<3, int, char>
应该解析为主要模板,但Widget<3, int, char, double>
应该解决专业化问题。
我尝试使用通常的SFINAE模式,但问题是模板参数包必须是最后一个模板参数,所以在typename... Ts
之后不可能插入SFINAE检查。
您可以使用帮助程序类:
// for your primary template
template<int n, bool b, class... Ts>
struct Widget_impl {};
// for your specialization
template<class... Ts>
struct Widget_impl<sizeof...(Ts), true, Ts...> {};
template<int n, typename... Ts>
using Widget = Widget_impl<n, n == sizeof...(Ts), Ts...>;
事实上,您的案例可以直接完成:
// for your primary template
template<int n, class... Ts>
struct Widget {};
// for your specialization
template<class... Ts>
struct Widget<sizeof...(Ts), Ts...> {};
因为sizeof...(Ts) == n
已经是专业化的情况。
你不能在typename... Ts
之后插入SFINAE支票,但你可以在之前插入:
template<typename AlwaysVoid, int n, typename... Ts>
struct WidgetImpl {};
// ...
template <int n, typename... Ts>
struct WidgetImpl<std::enable_if_t<sizeof...(Ts) == n>, n, Ts...> {
// ...
};
然后,您可以将其别名:
template <int n, typename... Ts>
using Widget = WidgetImpl<void, n, Ts...>;