Search code examples
c++googletest

How to check size of ::testing::Types template?


I'm creating a TYPED_TEST_SUITE and I want to get count of elements in ::testing::Types. The reason is to perform a static assertion, so I can be sure my tests are up to date with the source code.

With std::tuple following is possible:

int count = tuple_size<decltype(mytuple)>::value

Is there possibility to do the same with gtests's testing::Types? Or to convert std::tuple into testing::Types in a compile time?


Solution

  • Yes. You can do it this way:

    template<typename...>
    struct CountTypes;
    template<typename... Args>
    struct CountTypes<::testing::Types<Args...>> : std::integral_constant<int, sizeof...(Args)> {};
    
    template<typename...>
    struct ConvertTypes;
    template<typename... Args>
    struct ConvertTypes<::testing::Types<Args...>> { using type = std::tuple<Args...>;};
    
    int main()
    {
        using MyTypes = ::testing::Types<char, int>;
        static_assert(CountTypes<MyTypes>::value == 2);
        static_assert(std::is_same_v<ConvertTypes<MyTypes>::type, std::tuple<char, int>>);
        std::cout << CountTypes<MyTypes>::value << std::endl;
    }