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

杀马特。学长 韩版系。学妹 提交于 2019-12-03 03:13:05

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

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>

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