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