Why is this variadic function ambiguous?

后端 未结 3 1574
孤街浪徒
孤街浪徒 2020-12-11 09:48

This is related to my earlier post. I\'d like to know why one attempted solution didn\'t work.

template              /* A */
size_t num_         


        
3条回答
  •  情歌与酒
    2020-12-11 10:18

    Apropos the usefulness/uselessness of free variadic function templates: the usual use case for these is to have a variadic function parameter list, in which case a regular overload for the empty case will do just fine:

    size_t num_args()
    {
        return 0;
    }
    
    template  /* B */
    size_t num_args (H h, T... t)
    {
        return 1 + num_args(t...);
    }
    


    EDIT:

    As far as I can see, the following abuse of enable_if ought to work as a solution to your original question:

    #include 
    
    // Only select this overload in the empty case 
    template 
    typename std::enable_if<(sizeof...(T) == 0), size_t>::type
    num_args() 
    { 
        return 0;
    }
    
    template 
    size_t
    num_args() 
    {
        return 1 + num_args();
    }
    

    (Edit2: Reversed the order of the overloads to make the code actually compile)

提交回复
热议问题