c++模板:向编译器提示模板参数

C++ templates: Hint template arguments to compiler?

本文关键字:参数 提示 编译器 模板 c++      更新时间:2023-10-16

我有以下类定义:

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

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

更新到注释: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
}

你不能在编译时检查,所以assert是有序的

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