Writing variadic template constructor

前端 未结 4 743
无人共我
无人共我 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:35

    Totally agree with Brian's answer, but even though the right approach is another (i.e. use initializer_list) please be aware (for the sake of doing this correctly in other circumstances) that variadic template recursion in this case could be much simpler just by noting that an empty pack is a valid template parameter pack, so that the variadic template constructor will be called one final time with the empty pack, which will lead to trying to call a default ctor, which just can be defaulted and terminate the recursion.

    IOW, the following would work and would be much cleaner IMO:

    template 
    struct X
    {
        std::vector v;
        X() = default; //Terminating recursion
    
        template 
        X(U n, Ts... rest)  : X(rest...) { .. the recursive work ..}
    };
    

    Again, I'm not saying templates and recursion are the right thing here, I'm just pointing out that would they be necessary, there would be a simpler way to use them.

提交回复
热议问题