如何制作自定义关键字语句

How to make custom keyword statement

我将如何着手制作一个使用大括号的函数,如 if/for/while 语句?我将其称为 'keyword statement',因为我不知道还能称呼它什么。

意思是,例如,如果我想创建一个 'repeat' 函数:

repeat(3)
{
    //do something
}

我想一个更好的问题是,这可能吗?如果是这样,人们会怎么做呢?

您可以定义一个带 1 个参数的宏:

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

并将其后的括号留空,预处理器将扩展以下示例:

repeat(3)
{
    //do something
}

进入:

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

Demo

不要那样做 [#define repeat] - 不要试图改变您正在使用的编程语言的语法。这将使您的代码对其他人来说可读性大大降低。

您可以定义类似于 python 范围的范围:

// 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';
}

更复杂的实现也会考虑容器和迭代器。