1

I have the following class definition:

template<std::size_t N>
class Vector {
public:
    template<typename T>
    Vector(std::enable_if<is_foreach_iterator<T>, T>::type& it_begin, T& _end) {
        // At this point I can't figure out how to tell the compiler
        // that N = std::distance(it_begin, it_end)
    }
}

Is there a way I can somehow hint this to the compiler (and assert incorrect inputs?)

WorldSEnder
  • 4,875
  • 2
  • 28
  • 64
  • 1
    The compiler can't know that because the parameters are passed at runtime. You can always use `assert` for runtime assertions. – chris Jun 25 '14 at 20:46

1 Answers1

3

Update To the comments: Live On Coliru

#include <vector>

template <typename... Args>
    void foo(Args... args)
{
    static_assert(sizeof...(Args) == 7, "unexpected number of arguments");
    std::vector<int> v { args... };
}


int main(int argc, char* argv[])
{
    foo(1,2,3,4,5,6,7);
    foo(1,2,3,4,5,6,7,8); // oops
}

You can't check at compile time, so an assert is in order

#include <cassert>

template<std::size_t N>
class Vector {
public:
    template<typename T>
    Vector(std::enable_if<is_foreach_iterator<T>, T>::type& it_begin, T& _end) {
        assert(N == std::distance(it_begin, it_end));
    }
}

or, if you prefer

#include <stdexcept>

template<std::size_t N>
class Vector {
public:
    template<typename T>
    Vector(std::enable_if<is_foreach_iterator<T>, T>::type& it_begin, T& _end) {
        if(N != std::distance(it_begin, it_end))
           throw std::range_error();
    }
}
sehe
  • 374,641
  • 47
  • 450
  • 633
  • Is there a way I can tell the compiler that N = sizeof...(args)? I would so something like Vector(int&... args){n = sizeof...(args);}? This would be compile-time constant but I can't figure out how to do it that way. – WorldSEnder Jun 25 '14 at 20:59
  • You could use that iff you had a variadic argument (that would be checked at compile-time, yes). But your code doesn't have that. **Updated** answer: **[Live On Coliru](http://coliru.stacked-crooked.com/a/3a4c5e5708084e5d)** – sehe Jun 25 '14 at 21:04