jeudi 30 avril 2015

C++ range-for and boost::irange

I'm using boost::irange and created a helper function to simplify the code by removing the need for explicit template parameters. I don't understand why it doesn't work. Here's the code:

#include <iostream>
#include <boost/range/irange.hpp>

template<typename T>
boost::irange<T> range_from_zero(T limit)
{
    return boost::irange<T>(T(), limit);
}

int main() {
    size_t end = 100;
    for (auto i  : range_from_zero(0,end))
        std::cout << i << ' ';

    return 0;
}

There's a live version here http://ift.tt/1DMoQot, which produces compilation errors

prog.cpp:5:8: error: 'irange<T>' in namespace 'boost' does not name a type
 boost::irange<T> range_from_zero(T limit)
        ^
prog.cpp: In function 'int main()':
prog.cpp:12:41: error: 'range_from_zero' was not declared in this scope
     for (auto i  : range_from_zero(0,end))

If I use boost::irange directly in the range-for, then it works:

#include <iostream>
#include <boost/range/irange.hpp>

int main() {
    size_t end = 100;
    for (auto i  : boost::irange<size_t>(0,end))
        std::cout << i << ' ';

    return 0;
}

this works fine: http://ift.tt/1OI0bfd

I thought maybe is was a problem using range-for on the return of a function, but it isn't; this works using a std::vector:

#include <iostream>
#include <boost/range/irange.hpp>

template<typename T>
std::vector<T> range_from_zero(T limit)
{
    auto range = boost::irange<T>(T(), limit);
    return { std::begin(range), std::end(range) };
}

int main() {
    size_t end = 100;
    for (auto i : range_from_zero(end))
        std::cout << i << ' ';

    return 0;
}

See http://ift.tt/1DMoOgf

Any ideas, please?

Aucun commentaire:

Enregistrer un commentaire