gpt4 book ai didi

c++ - 为什么我们不能在模板特化的开始/中间使用可变参数模板(以及如何模拟)?

转载 作者:行者123 更新时间:2023-11-30 03:26:40 25 4
gpt4 key购买 nike

我想知道如何模拟以下内容:

template<class> struct foo; 

template<template<class..., int..., class...> class list,
class... clist1, int... ilist1, class... clist2>
struct foo<list<clist1..., ilist1..., clist2...>> {

};

此特化(假设)接受 class有任意数量的类,然后是整数,然后是类。目前似乎没有办法直接实现这一点。 (如果你能评论为什么标准不支持这个,加分)

Eigen 的线性代数库中的一个例子说明了这何时可行,其中大多数类的结构如下:

Vector<class Scalar_type, int rows, class... options>
Mstrix<class Scalar_type, int rows, int cols, class... options>

启用上述功能后,可以使用接受任何这些基类的元模板函数。因为它不受支持,所以您必须为每个类编写特化。

有什么方法可以模拟支持接受上述类的模板函数吗?

我正在寻找一个通用的解决方案。 (每个类都写特化不是通用的,我也不是直接找Eigen的库解决,那只是个例子)


说明示例

假设我想获得 template class 的头等舱.我以某种方式从其他一些元模板函数中获取了原始类类型。因此,我不知道它的模板参数是什么样的。

也许是:

Vector1<class Scalar_type, int rows, class... others>或者

Vector2<class Scalar_type, class... others>

因为我没有直接使用类型,所以我的元模板函数必须是类似 template<class> struct foo; 的类型有各种专业。

在这种情况下 getFront是一个很好的例子,因为我需要 2 个专业:

template<class> struct getFront; 

template<template<class...,int...,class...> class param,
class... l1, int... l2, class... l3, class first>
struct getFront<param<first, l1..., l2... l3....> {
using type = first; };

template<template<class...> class param, class first, class... others>
struct getFront<param<first, others...>> {
using type = first;
};

最佳答案

Is there any way to emulate a template function that supports accepting classes like the above?

如下使用模板特化怎么样?

template <typename...>
struct foo;

template <typename ... Ts1, int ... Is, typename ... Ts2>
struct foo<std::tuple<Ts1...>,
std::integer_sequence<int, Is...>,
std::tuple<Ts2...>>
{
};

或者,如果你更喜欢参数化模板容器,比如

template <template <typename...> class Ct1, typename ... Ts1,
template <int...> class Ci, int ... Is,
template <typename...> class Ct2, typename ... Ts2>
struct foo<Ct1<Ts1...>, Ci<Is...>, Ct2<Ts2...>>
{ };

关于c++ - 为什么我们不能在模板特化的开始/中间使用可变参数模板(以及如何模拟)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48130828/

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