Writing variadic template constructor

前端 未结 4 739
无人共我
无人共我 2021-02-02 10:38

Recently I asked this question but now I would like to expand it. I wrote the following class:

template 
class X{
public:
    vector v;
          


        
4条回答
  •  说谎
    说谎 (楼主)
    2021-02-02 11:16

    There is no need for recursion in the first place -
    you can use the "temporary array" idiom and write

    template 
    X(E&&... e) {
        int temp[] = {(v.push_back(e), 0)...};
    }
    

    The proper (and more complicated) version of this approach looks like this:

    template 
    X(E&&... e) {
        (void)std::initializer_list{(v.push_back(std::forward(e)), void(), 0)...};
    }
    

    Live version

    Note, than the next version of C++ will probably have the Fold Expressions
    (v.push_back(e), ...);

提交回复
热议问题