Is there a way to check std :: initializer_list for the number of arguments at compile time?

I am trying to create a function that will take several arguments of a given type, but the type and number of arguments must be specified using templates.

I found that using the C ++ 11 initializer_list initializer_list is probably a good technique in this case, but is it possible to check its size at compile time? Are there any other methods that can solve this problem?

#include <initializer_list>

// Here I want to define type and number of components for each point

template <typename T, int DIM>
class Geometry
{
public:
    void addPoint(std::initializer_list<T> coords)
    {
        assert(coords.size() == DIM); // Working good, but not compile-time

        // Next line does not compile because size() is not known at compile-time
        static_assert(coords.size() == DIM, "Wrong number of components"); 
    }
};
+4
source share
3 answers

. initializer_list , .

constexpr , .

.

+6

Nicol . , , , . . GCC 4.9.

template<class T, class...>
struct are_convertible : std::true_type
{};

template<class T, class U, class... TT>
struct are_convertible<T, U, TT...>
    : std::integral_constant<bool, std::is_convertible<T,U>{} && are_convertible<T, TT...>{}>
{};

template <typename T, int DIM>
class Geometry
{
public:
    template<typename... Args>
    void addPoint(Args... coords)
    {
        static_assert(sizeof...(coords) == DIM, "Number of components does not match template");
        static_assert(are_convertible<T, Args...>{}, "All arguments' types must be convertible to the template type"); 
    }
};
+2

Adding a POD Class A point with DIM data members does not meet your purpose. Then an implicit constructor call will ensure that everything is in order.

+2
source

Source: https://habr.com/ru/post/1621652/


All Articles