如何制作自定义关键字声明

时间:2015-10-13 19:29:21

标签: c++ function curly-braces

我如何创建一个使用if / for / while语句等大括号的函数?我将此称为关键字声明'因为我不知道还有什么可以称之为。

意思是,例如,如果我想重复一次'功能:

repeat(3)
{
    //do something
}

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

3 个答案:

答案 0 :(得分:6)

不要那样做[#define repeat] - 不要试图改变你正在使用的编程语言的语法。这将使您的代码对其他任何人来说都不那么容易理解。

答案 1 :(得分:6)

您可以定义类似于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';
}

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

答案 2 :(得分:3)

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

repeat(3)
{
    //do something
}

并将bracoets留空,预处理器将扩展以下示例:

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

成:

{{1}}

<强> Demo