gpt4 book ai didi

c++ - 推导嵌套模板可变非类型列表的类型

转载 作者:太空狗 更新时间:2023-10-29 23:18:19 25 4
gpt4 key购买 nike

考虑以下类:

template<class T, int...> struct MyClass1 {};
template<class T, unsigned int...> struct MyClass2 {};
template<class T, long long int...> struct MyClass3 {};
template<class T, unsigned long long int...> struct MyClass4 {};

我不能修改这些类。

是否可以编写一个辅助类或函数之类的东西,它将返回可变参数列表的类型:

something<MyClass1>::type (-> int)
something<MyClass2>::type (-> unsigned int)
something<MyClass3>::type (-> long long int)
something<MyClass4>::type (-> unsigned long long int)

size_t 如果可变参数列表为空?

最佳答案

我无法想出一种方法来定义执行此操作的一个通用元函数,但这里有一个可能的解决方法:

#include <iostream>
#include <type_traits>

using namespace std;

// PRIMARY TEMPLATE

template<typename T>
class something
{
};

// SPECIALIZATIONS FOR int

template<typename T, int... U, template<typename, int...> class L>
class something<L<T, U...>>
{
public:
typedef int type;
};

template<typename T, template<typename, int...> class L>
class something<L<T>>
{
public:
typedef size_t type;
};

// SPECIALIZATIONS FOR unsigned int

template<typename T, unsigned int... U, template<typename, unsigned int...> class L>
class something<L<T, U...>>
{
public:
typedef unsigned int type;
};

template<typename T, template<typename, unsigned int...> class L>
class something<L<T>>
{
public:
typedef size_t type;
};

/* ... OTHER SPECIALIZATIONS ... */

struct A {};
struct B {};

int main()
{
static_assert(is_same<something<MyClass1<A, 1, 2>>::type, int>::value, "Error!");
static_assert(is_same<something<MyClass1<A>>::type, size_t>::value, "Error!");
static_assert(is_same<something<MyClass2<B, 1U, 2U, 3U>>::type, unsigned int>::value, "Error!");
static_assert(is_same<something<MyClass2<B>>::type, size_t>::value, "Error!");
return 0;
}

我试着只写一个涵盖所有情况的特化,像这样:

template<typename U, typename T, U... V, template<typename, U...> class L>
class something<L<T, V...>>
{
public:
typedef U type;
};

但 Clang 3.2 提示无法推断出 U 的类型,因此永远不会使用 get_type 的这种特化。因此,如果您采用这种方法,则必须明确定义每个特化。根据您的用例,这可能会或可能不会被接受。希望对您有所帮助。

关于c++ - 推导嵌套模板可变非类型列表的类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14057002/

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