如何基于数组的元素自动创建模板类的元组
How to automate creation of tuples of template classes based on elements of an array?
我有一个std::array
,它填充了枚举的所有类型。我想实现基于元组的关于这个。
class CompBase
{
public:
enum CompType{
INPUT,
GRAPHICS
// ( + 5-10 additional types)
};
static const std::array<CompType, 2> compTypeArr;
};
const std::array<CompBase::CompType, 2> CompBase::compTypeArr =
{
CompBase::INPUT,
CompBase::GRAPHICS
};
template<CompBase::CompType compType_e>
class CompHolder {}; // owns one component
template<CompBase::CompType compType_e>
class CompContainer {}; // references N components
class CompInterface
{
// ...
private:
std::tuple // I want to automate this,
<
CompHolder<CompBase::INPUT>,
CompHolder<CompBase::GRAPHICS>
> compHolders;
};
class CompHandler
{
// ...
private:
std::tuple // and this process, based on the predefined array
<
CompCont<CompBase::INPUT>,
CompCont<CompBase::GRAPHICS>
> compContainers;
};
据我所知,std::make_tuple
在c++14
引用之前甚至不是constexpr
所以我不确定这是否可能,因为我需要一个c++11
方法。数组的存在我认为是强制性的,因为单独的枚举并不能为类似的事情提供必要的功能。
这里有一个在C++11中工作的解决方案。正如在评论中所讨论的,使用std::array
将在C++14中工作,其中它的常量访问器被设置为constexpr
。
#include <tuple>
#include <type_traits>
#include <iostream>
class CompBase
{
public:
enum CompType {
INPUT,
GRAPHICS
// ( + 5-10 additional types)
};
};
template<CompBase::CompType...> struct CTLHelper;
using CompTypeList = CTLHelper<
CompBase::INPUT,
CompBase::GRAPHICS
>;
template<template<CompBase::CompType> class, class> struct CompTupleMaker;
template<template<CompBase::CompType> class H, CompBase::CompType... Es>
struct CompTupleMaker<H, CTLHelper<Es...>>
{
using type = std::tuple<H<Es>...>;
};
template<CompBase::CompType compType_e>
class CompHolder {}; // owns one component
template<CompBase::CompType compType_e>
class CompContainer {}; // references N components
using CompHolderTuple = CompTupleMaker<CompHolder, CompTypeList>::type;
using CompContainerTuple = CompTupleMaker<CompContainer, CompTypeList>::type;
class CompInterface
{
// ...
private:
CompHolderTuple compHolders;
};
class CompHandler
{
// ...
private:
CompContainerTuple compContainers;
};
int main()
{
// just a quick check
std::cout << std::is_same<CompHolderTuple, std::tuple<CompHolder<CompBase::INPUT>, CompHolder<CompBase::GRAPHICS>>>::value << 'n';
}
如果在C++11中的数组中确实需要这些枚举器,可以使用声明为constexpr
的内置数组——可以在常量表达式中引用其元素。我想说,只有当你也需要数组来做其他事情时,这才有意义;如果您只需要一个枚举器列表的持有者,那么在这种情况下,variadic解决方案会更简单。对于阵列解决方案,您需要类似于C++14的std::index_sequence
的东西来扩展阵列。
相关文章:
- C++:TypeDef使用元组
- Pybind11:将元组列表从Python传递到C++
- 重载元组索引运算符-C++
- 在C++中,如何通过几种类型从元组中选择多个元素
- 将fold表达式与std::一起用于两个元组
- std::ranges::elements_view,用于自定义类似元组的数据
- 将元组的向量转换/构造为堆
- 专用于 std 元组的模板,而无需用户执行remove_cvref
- 将元组的向量构造成堆
- 元组由 Swig 生成的 Python 包装器返回,用于C++向量
- 将元组类型扩展为可变参数模板?
- 时间复杂度 当具有复合数据类型(如元组或对)时?
- 类内部和外部静态 constexpr 元组之间的差异
- 可变参数模板与使用元组在参数中添加不同的数据对
- 访问和打印元组中的数据,并使用 C++14 使用模板函数显示数据
- boost::包含提升单元的元组的哈希值
- 我正在寻找一种优雅的方式来从元组向量创建tuple_element向量
- 如何在可变参数模板函数中遍历可变参数元组?
- 如何使用 SML 随机生成八进制元组
- 元组的运行时索引