簡體   English   中英

通過 std::type_identity 從 std::tuple 獲取值

[英]Get value from std::tuple by std::type_identity

我正在嘗試編寫一個 function,它將通過一種特殊類型從元組中獲取一個值,可以通過繼承 std::type_identity<special_type> 來標記多種類型。

我想讓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;
}();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM