Get index by type in std::variant

前端 未结 5 1190
暗喜
暗喜 2020-12-10 13:19

Is there a utility in the standard library to get the index of a given type in std::variant? Or should I make one for myself? That is, I want

5条回答
  •  不思量自难忘°
    2020-12-10 14:14

    You can also do this with a fold expression:

    template 
    constexpr size_t get_index(std::variant const&) {
        size_t r = 0;
        auto test = [&](bool b){
            if (!b) ++r;
            return b;
        };
        (test(std::is_same_v) || ...);
        return r;
    }
    

    The fold expression stops the first time we match a type, at which point we stop incrementing r. This works even with duplicate types. If a type is not found, the size is returned. This could be easily changed to not return in this case if that's preferable, since missing return in a constexpr function is ill-formed.

    If you dont want to take an instance of variant, the argument here could instead be a tag>.

提交回复
热议问题