WorldSEnder
WorldSEnder

Reputation: 5044

C++ templates: Hint template arguments to compiler?

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?)

Upvotes: 1

Views: 1588

Answers (1)

sehe
sehe

Reputation: 393084

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();
    }
}

Upvotes: 3

Related Questions