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

后端 未结 2 1958
南方客
南方客 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<typename...>
    struct are_same : std::true_type 
    {};
    
    template<typename T>
    struct are_same<T> : std::true_type
    {};
    
    template<typename T, typename U, typename... Types>
    struct are_same<T, U, Types...> :
        std::integral_constant<bool, (std::is_same<T, U>::value && are_same<T, Types...>::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 <unsigned int N> class myclass
    {
    public:
        template <typename... Args>
        typename std::enable_if<(are_same<double, Args...>::value && sizeof...(Args) == N), void>::type
        /* void */ mymethod(Args... args)
        {
            // Do interesting stuff
        } 
    };
    
    0 讨论(0)
  • 2021-02-05 20:02

    Can try something like following :

    #include <type_traits>
    
    template<class T, class...>
    struct all_same : std::true_type
    {};
    
    template<class T, class U, class... TT>
    struct all_same<T, U, TT...>
        : std::integral_constant<bool, std::is_same<T,U>{} && all_same<T, TT...>{}>
    {};
    
    
    template <unsigned int N> class myclass
    {
        public:
        template <typename... Args>
         typename std::enable_if<sizeof...(Args) == N, void >::type mymethod(Args... args)
        {
            static_assert(all_same<double, Args...>{}, 
                          "Not all args as Double");
        }
    };
    

    <Demo>

    0 讨论(0)
提交回复
热议问题