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

孤者浪人 提交于 2019-12-03 11:57:53

问题


template <unsigned int N> class myclass
{
public:
    template <typename... Args> void mymethod(Args... args)
    {
       // Do interesting stuff
    } 
};

I want mymethod to be called only with exactly N doubles. Is that possible? That is, say that I have:

myclass <3> x;
x.mymethod(3., 4., 5.); // This works
x.mymethod('q', 1., 7.); // This doesn't work
x.mymethod(1., 2.); // This doesn't work

How can I get this done?


回答1:


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
    } 
};



回答2:


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>



来源:https://stackoverflow.com/questions/30179181/a-variadic-template-method-to-accept-a-given-number-of-doubles

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!