gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 01:04:58 25 4
gpt4 key购买 nike

采用以下模板结构:

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

其实你的case可以直接搞定:

// 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 已经是特化了。

关于c++ - 如何为特定数量的模板参数专门化可变参数模板结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49120155/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com