Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Any way to check count of template parameters at compile time?

Is there any way to check number of template parameters and compile time? I would like to do this (this is not real code):

template<typename... Types>
class Foo
{
    // Enable this if count of 'Types' is 1.
    Types[0] Bar()
    {
        return Types[0]{};
    }
    
    // Enable this otherwise.
    std::variant<Types> Bar()
    {
        return std::variant<Types>{};
    }

};

Is there any way to achieve this?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

One option is to add a template parameter and then leverage constexpr if to check if the pack is empty or not like

template<typename first_t, typename... rest_t>
class Foo
{
    auto Bar()
    {
        if constexpr (sizeof...(rest_t) == 0)
            return first_t{};
        else
            return std::variant<first_t, rest_t...>{};
    }
};
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading