简体   繁体   English

C ++与部分模板专业化语法混淆

[英]C++ confused with partial template specialization syntax

Is there a way I could avoid using Range2 as a name and have both classes named Range ? 有没有一种方法可以避免使用Range2作为名称并使两个类都命名为Range I'm a bit confused with the C++ template syntax. 我对C ++模板语法有点困惑。

template <int BEGIN, int END>
class Range2
{
public:
    class Iterator
    {
    private:
        int n;

    public:
        Iterator(int n)
            : n(n)
        {
        }

        int operator *() const
        {
            return n;
        }

        Iterator const & operator ++()
        {
            ++n;
            return *this;
        }

        bool operator !=(Iterator const & i) const
        {
            return n != i.n;
        }
    };

    Iterator begin() const
    {
        return Iterator(BEGIN);
    }

    Iterator end() const
    {
        return Iterator(END);
    }
};

template<int END>
class Range
    : public Range2<0, END>
{
};

As with function arguments, in C++ template arguments can have a default value. 与函数自变量一样,在C ++模板中自变量可以具有默认值。 The only thing you will have to pay for this putting the END, which has no default value, before the BEGIN, which has 0 as default. 您唯一需要为此付出的就是将没有默认值的END放到默认值为0的BEGIN之前。

// Here we add the default parameter to BEGIN
// The arguments are switched because END is without a default       
// parameter, so it has to come before BEGIN that has one
template <int END, int BEGIN=0>
// The class itself is the same, but now you can use it
// without giving a BEGIN parameters
class Range
{
public:
    class Iterator
    {
    private:
        int n;

    public:
        Iterator(int n)
            : n(n)
        {
        }

        int operator *() const
        {
            return n;
        }

        Iterator const & operator ++()
        {
            ++n;
            return *this;
        }

        bool operator !=(Iterator const & i) const
        {
            return n != i.n;
        }
    };

    Iterator begin() const
    {
        return Iterator(BEGIN);
    }

    Iterator end() const
    {
        return Iterator(END);
    }
};

It compiles and should work as intended. 它可以编译并应按预期工作。 Without a main, I wasn't able to test it, though. 没有主电源,但是我无法对其进行测试。

EDIT: I added some comments and here an example of usage, just for clarity: 编辑:我添加了一些评论,这里是一个用法示例,只是为了清楚起见:

Range<10, 3> r(3); /*here we use it as usual, pay attention begin is 
                     now the second argument and not the first */
Range<10> r(0);    /* here we don't give a BEGIN argument, the 
                      compiler will use the default one */

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM