簡體   English   中英

C ++與部分模板專業化語法混淆

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

有沒有一種方法可以避免使用Range2作為名稱並使兩個類都命名為Range 我對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>
{
};

與函數自變量一樣,在C ++模板中自變量可以具有默認值。 您唯一需要為此付出的就是將沒有默認值的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);
    }
};

它可以編譯並應按預期工作。 沒有主電源,但是我無法對其進行測試。

編輯:我添加了一些評論,這里是一個用法示例,只是為了清楚起見:

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