使用参数包和模板函数以差异为未命名的结构

问题描述 投票:0回答:1

template<typename T> concept myrequirement= requires(T s) { { s.type() } -> std::same_as<uint8_t>; }; enum MyType { TYPE1, TYPE2, TYPE3, };

因此,我的用户可以编写不满意的结构,以满足此要求:

struct
{
    static constexpr uint8_t type() { return TYPE1;}
} foo;

struct
{
    static constexpr uint8_t type() { return TYPE2;}
} bar;

struct
{
    static constexpr uint8_t type() { return TYPE3;}
} baz;

我希望用户能够根据其类型字段来检索正确的未固定结构:

auto my_struct = get_instance<TYPE1>();

我以为我可以使用C ++的Pack参数来写下类似的内容:

template<uint8_t type, myrequirement... StructTypes> 
constexpr auto& get_instance_amongst(const StructTypes&... structs)
{
    // how do we do this ?
}

template<uint8_t type>
constexpr auto& get_instance()
{
    return get_instance_amongst(foo, bar, baz);
}
我尝试了很多代码,但似乎没有任何编译... 有什么可能吗?折叠表达方式可能?

In

get_instance_amongst

,您可以使用the将返回实例上参考文献的元组,然后使用
c++ templates fold pack unnamed-class
1个回答
0
投票
获取给定索引所需的实例。因此,您可以选择这样的事情:

std::get
demo

    
	

最新问题
© www.soinside.com 2019 - 2025. All rights reserved.