我正在尝试编写一个函数,该函数将通过特殊类型从元组中获得一个值,多个类型可以通过继承std::type_identity
我想让Things::GetThing()
在下面工作。
使用c++ 20是可以的。
这可能吗?
#include <type_traits>
#include <tuple>
template<typename...Types>
class Things
{
public:
template<typename T>
auto& GetThing() {
// what to do here?
}
private:
std::tuple<Types...> things{};
};
struct FooType {};
struct FooA : std::type_identity<FooType> {};
struct FooB : std::type_identity<FooType> {};
struct Bar {};
int main()
{
{
Things<FooA, Bar> things1;
auto& foo = things1.GetThing<FooType>();
static_assert(std::is_same_v<decltype(foo), FooA&>);
}
{
Things<FooB, Bar> things2;
auto& foo = things2.GetThing<FooType>();
static_assert(std::is_same_v<decltype(foo), FooB&>);
}
}
先查找索引,然后使用std::get<index>(tuple)
获取正确的元素
在&&
或||
上使用折叠表达式是获得索引的一种方法。注意,这里使用了一个立即调用的lambda将index
转换为编译时常量。
constexpr std::size_t index = []{
std::size_t index = 0;
((std::is_base_of_v<std::type_identity<T>, Types> || (index++, false)) || ...);
return index;
}();