Search code examples
c++templatesc++11initializer-listcompile-time

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


I am trying to create a function that would accept several arguments of a given type, but both type and number of arguments should be specified via templates.

I found that using C++11's 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 tecnhiques 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"); 
    }
};

Solution

  • You cannot statically assert on a runtime quantity. And the number of values in an initializer_list is decided at runtime, by the caller of the function.

    Not even making your function constexpr would work, since evaluation of the function is not required to take place at compile-time.

    You should instead use a variadic template.