如何为特定数量的模板参数专门化可变参数模板结构



采用以下模板结构:

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...>;

最新更新