我有以下的类别定义:
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)
}
}我是否可以以某种方式向编译器提示这一点(并断言不正确的输入?)
发布于 2014-06-25 20:47:30
更新到注释:住在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();
}
}https://stackoverflow.com/questions/24418178
复制相似问题