【发布时间】:2023-04-02 17:25:01
【问题描述】:
有什么方法可以让我拥有可变参数对吗?我的目标是为每种类型添加额外的信息。
类似这样的:
// non compilable code
// I want to pass an extra uint8_t with each type here.
template<template<typename EnumType, uint8_t Bitmask> typename... EnumsAndBitmasks>
void func(){
// Unpack EnumsAndBitmasks and do something with pairs of each EnumType and it's Bitmask
}
// Call func like this
enum class Type1 : uint8_t;
enum class Type2 : uint8_t;
enum class Type3 : uint8_t;
func<<Type1,0x03>, <Type2,0x3C>, <Type3,0xC0>>();
以下是非模板化的工作代码,但我想通过提供返回结构类型和每个 EnumType 及其位掩码作为unpack_from_single_byte 函数的模板参数来概括这个过程。
enum class EnumType1 : uint8_t { first, second };
enum class EnumType2 : uint8_t { first, second, third, forth };
enum class EnumType3 : uint8_t { first, second };
struct Unpacked
{
EnumType1 var1;
EnumType2 var2;
EnumType3 var3;
};
Unpacked unpack_from_single_byte(uint8_t value)
{
return { static_cast<EnumType1>(value & 0x01),
static_cast<EnumType2>(value & 0x06),
static_cast<EnumType3>(value & 0x0F) };
}
【问题讨论】:
标签: c++ templates variadic-templates