1

我有以下类定义:

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

有没有办法可以以某种方式向编译器提示这一点(并断言不正确的输入?)

4

1 回答 1

3

更新评论: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
}

你不能在编译时检查,所以一个断言是有序的

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

或者,如果您愿意

#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();
    }
}
于 2014-06-25T20:47:30.373 回答