A variadic template method to accept a given number of doubles?

后端 未结 2 1957
南方客
南方客 2021-02-05 19:06
template  class myclass
{
public:
    template  void mymethod(Args... args)
    {
       // Do interesting stuff
    } 
};
         


        
2条回答
  •  野性不改
    2021-02-05 19:46

    For the number of arguments constraint you can easily check if sizeof...(Args) == N but for checking if all the arguments are doubles you need to build a recursive type trait that checks std::is_same for each of the arguments.

    template
    struct are_same : std::true_type 
    {};
    
    template
    struct are_same : std::true_type
    {};
    
    template
    struct are_same :
        std::integral_constant::value && are_same::value)>
    {};
    

    Notice are_same is first declared and then specialized.

    Then just implement the constraint in your method return type using std::enable_if by taking advantage of SFINAE.

    template  class myclass
    {
    public:
        template 
        typename std::enable_if<(are_same::value && sizeof...(Args) == N), void>::type
        /* void */ mymethod(Args... args)
        {
            // Do interesting stuff
        } 
    };
    

提交回复
热议问题