lundi 26 février 2018

Avoid template overloading in c++

template<int ... p>
class Separate {
private:
    int range;
    vector<int> pos{p...};

    template<int end>
    void _split(int cur) {
        for (int i = cur; i < end; i++)
            cout << " " << i;
        cout << endl;
        for (int i = end; i < range; i++)
            cout << " " << i;
        cout << endl;
    }

    template<int end, int... args>
    void _split(int cur) {
        for (int i = cur; i < end; i++)
            cout << " " << i;
        cout << endl;
        _split<args...>(end);
    }

    void _split1(int cur, vector<int>::iterator iterator) {

        if (iterator == pos.end())
            _split1(cur);
        else {
            int end = *iterator;
            for (int i = cur; i < end; i++)
                cout << " " << i;
            cout << endl;
            _split1(end, ++iterator);
        }
    }

    void _split1(int cur) {
        for (int i = cur; i < range; i++)
            cout << " " << i;
        cout << endl;
    }

public:
    explicit Separate(int r) : range(r) {}

    void split() {
        _split<p...>(0);
        _split1(0, pos.begin());
    }
};

int main() {
    Separate<1, 4> a(6);
    a.split();
/* 0
 * 1 2 3
 * 4 5
 * */

    Separate<> b(2);
    b.split();
/* 0 1 
 * */

I use the normal way to show what I want to.And the hardest part is resolving function overloading and match empty template args.I want to do this because I see something similar to annotation in java.Use template to describe where will Separate class split.

Aucun commentaire:

Enregistrer un commentaire