简体   繁体   中英

Type-dependent range-based inserter function

I would like to maintain a range-based and type-dependent method for insertion in my class.

The question is how you can implement this type-dependency by using iterators.

The following pseudo code should explain my problem:

class Test {

public:
    template<typename Iterator>
    void insert(const uint8 position, const Iterator begin, const Iterator end) {
        std::copy(begin, end, std::inserter(m_deque, m_deque.begin());
    }


private:
    std::deque<uint8> m_deque;

};


int main() {

    Test t;

    uint8 dataone[] = {0x00, 0xff};
    uint16 datatwo[] = {0xff, 0x00};
    std::vector<uint8> vecdataone = {0x00, 0xff};
    std::vector<uint16> vecdatatwo = {0xff, 0x00};

    t.insert(0, dataone, dataone + 2); // OKAY
    t.insert(0, datatwo, datatwo + 2); // SHOULD CAUSE AN ERROR
    t.insert(0, vecdataone.cbegin(), vecdataone.cend()); // OKAY
    t.insert(0, vecdatatwo.cbegin(), vecdatatwo.cend()); // SHOULD CAUSE AN ERROR

}

Greets.

A static assertion will do the job:

void insert(const uint8 position, const Iterator begin, const Iterator end)
{
    static_assert(
        std::is_same<
            typename std::iterator_traits<Iterator>::value_type,
            uint8_t
        >::value,
        "Need iterators to uint8_t!"
    );
    // ....
}

I'd also suggest to use deque 's own insert function instead of std::copy :

 m_deque.insert(s.deque.begin() + position, begin, end);

Being a member function and thus aware of internals, it can do a better job at optimizing the insertion.

I like (and upvoted) jrok's answer, but here's another approach using SFINAE, which means you can potentially allow matching to some other insert overrides if that makes sense. Error messages may be more cryptic than for jrok's answer though.

template<typename Iterator>
typename std::enable_if<
             std::is_same<typename std::iterator_traits<Iterator>::value_type,
                          uint8>::value,
             void>::type 
insert(const uint8 position, const Iterator begin, const Iterator end)
    ...

demo at http://ideone.com/c1d9jT

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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