Variable length template arguments list?

后端 未结 4 1537
情话喂你
情话喂你 2021-02-01 10:03

I remember seing something like this being done:

template 
class X : public ListOfTypenames {};

that is, X inherits from

4条回答
  •  长情又很酷
    2021-02-01 10:54

    You can do it in current C++. You give the template a "large enough" number of parameters, and you give them defaults:

    class nothing1 {};
    class nothing2 {};
    class nothing3 {};
    
    template 
    class X : public T1, public T2, public T3 {};
    

    Or you can get more sophisticated and use recursion. First you forward-declare the template:

    class nothing {};
    
    template 
    class X;
    

    Then you specialise for the case where all the parameters are default:

    template <>
    class X {};
    

    Then you properly define the general template (which previously you've only forward-declared):

    template 
    class X : public T1, public X
    

    Notice how in the base class, you inherit X but you miss the first parameter. So they all slide along one place. Eventually they will all be defaults, and the specialization will kick in, which doesn't inherit anything, thus terminating the recursion.

    Update: just had a strange feeling I'd posted something like this before, and guess what...

提交回复
热议问题