Concatenating C++ iterator ranges into a const vector member variable at construction time

后端 未结 5 1364
情歌与酒
情歌与酒 2020-12-19 06:42

I have a class X, which I provide a snippet of here:

class X {
  public:
    template 
    X(Iter begin, Iter end) : mVec(begin, end) {}         


        
5条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-19 07:20

    One of the best or worst features of C++, depending on your viewpoint, is that you can abuse it when necessary to get the job done. In this case, const_cast is the victim:

    template 
    X(Iter1 begin1, Iter1 end1, Iter2 begin2, Iter2 end2) : mVec(begin1, end1) {
        const_cast&>(mVec).insert(mVec.end(), begin2, end2);
    }
    

    I might have some of the details wrong, I didn't try to compile this. But it should give you the idea.

提交回复
热议问题