Check if parameter pack contains a type

后端 未结 3 978
孤街浪徒
孤街浪徒 2020-12-16 05:15

I was wondering if C++0x provides any built-in capabilities to check if a parameter pack of a variadic template contains a specific type. Today, boost:::mpl::contains can be

3条回答
  •  佛祖请我去吃肉
    2020-12-16 05:40

    Fortunately, the C++ standard has evolved. With C++1z aka C++17, you can finally iterate easily over parameter packs. So the code for the answer is (almost) as simple, as suggested in the question:

    template
    struct is_present {
        static constexpr bool value {(std::is_same_v || ...)};
    };
    

    The weird-looking (std::is_same_v || ...) is expanded by the compiler internally to (std::is_same_v || std::is_same_v || ...), which is exactly, what you want. It even correctly yields false with an empty Args parameter pack.

    It is even possible to do the whole check inline in a function or method - no helper structs are required anymore:

    template
    void foo(T t, List ... lst)
    {
        if constexpr((std::is_same_v || ...)) {
            std::cout << "T is in List" << std::endl;
        } else {
            std::cout << "T is not in List" << std::endl;
        }
    }
    

    Note: This has been taken from another question, that was marked as a duplicate of this question. As this is the "canonical" question for this topic, I added that important information here.

提交回复
热议问题