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

问题描述 投票:1回答:2

采用以下模板结构:

template<int n, typename... Ts>
struct Widget {};

如何专注于sizeof...(Ts) == n的情况?例如。 Widget<3, int, char>应该解析为主要模板,但Widget<3, int, char, double>应该解决专业化问题。

我尝试使用通常的SFINAE模式,但问题是模板参数包必须是最后一个模板参数,所以在typename... Ts之后不可能插入SFINAE检查。

c++ c++11 templates metaprogramming variadic-templates
2个回答
3
投票

您可以使用帮助程序类:

// 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已经是专业化的情况。


2
投票

你不能在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...>;
© www.soinside.com 2019 - 2024. All rights reserved.