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?

>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...>{};
    }
};

Leave a Reply