How to make custom keyword statement

余生长醉 提交于 2019-12-04 20:26:36

You might define a range similar to a python range:

// Range
// =====

#include <iterator>
#include <utility>

template<typename T>
class Range
{
    public:
    typedef T value_type;

    public:
    class iterator
    {
        public:
        typedef typename std::forward_iterator_tag iterator_category;
        typedef typename std::size_t size_type;
        typedef typename std::ptrdiff_t difference_type;
        typedef T value_type;
        typedef const T& reference;
        typedef const T* pointer;

        public:
        iterator(const T& value) noexcept
        :   m_value(value)
        {}

        reference operator * () const noexcept { return m_value; }
        pointer operator -> () const noexcept { return &m_value; }
        iterator& operator ++ () noexcept { ++m_value; return *this; }

        friend bool operator == (const iterator & a, const iterator b) noexcept {
            return a.m_value == b.m_value;
        }
        friend bool operator != (const iterator & a, const iterator b) noexcept {
            return a.m_value != b.m_value;
        }

        private:
        T m_value;
    };

    public:
    Range(const T& first, const T& last) noexcept
    :   m_first(first), m_last(last)
    {}

    Range(T&& first, T&& last) noexcept
    :   m_first(std::move(first)), m_last(std::move(last))
    {}

    Range(Range&& other) noexcept
    :   m_first(std::move(other.m_first)),
        m_last(std::move(other.m_last))
    {}

    Range& operator = (Range&& other) noexcept {
        m_first = std::move(other.m_first);
        m_last = std::move(other.m_last);
        return *this;
    }

    iterator begin() const noexcept { return  m_first; }
    iterator end() const noexcept { return m_last; }

    private:
    T m_first;
    T m_last;
};

template<typename T>
inline Range<T> range(T&& first, T&& last) noexcept {
    return Range<T>(std::move(first), std::move(last));
}


// Test
// ====

#include <iostream>

int main() {
    for(auto i : range(0, 3))
        std::cout << i << '\n';
}

A more sophisticated implementation would consider containers and iterators, too.

Don't do that [#define repeat] - don't try to change the syntax of the programming language you're using. That will make your code far less readable for anyone else.

You could define a macro taking 1 argument:

#define repeat(COUNT) \
    for (unsigned int i = 0; i < (COUNT); ++i)

and leave the brakets empty after it, the preprocessor will expand the following example:

repeat(3)
{
    //do something
}

into:

for (unsigned int i = 0; i < (3); ++i)
{
    //do something
}

Demo

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!