如何制作自定义关键字声明 [英] How to make custom keyword statement
本文介绍了如何制作自定义关键字声明的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我该如何制作一个使用大括号的函数,例如if/for/while语句?我将此称为关键字声明",因为我不知道该怎么称呼.
How would I go about making a function that uses braces like if/for/while statements? I'm referring to this as a 'keyword statement' because I don't know what else to call it.
举例来说,如果我想做一个重复"功能:
Meaning, for example, if I wanted to make a 'repeat' function:
repeat(3)
{
//do something
}
我想一个更好的问题是,这可能吗?如果是这样,人们将如何去做呢?
I guess a better question is, is this possible? If so, how would one go about doing this?
推荐答案
您可以定义类似于python范围的范围:
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.
这篇关于如何制作自定义关键字声明的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文