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 に答える