Search code examples
c++templatesc++14variadic-templatestemplate-meta-programming

C++14. Declare a function with same-type-and-fixed-length argument list


Is there a possible way to implement sort of helper struct using C++14 which takes as a template argument a Number, return type Ret and input type T and would contain a member type std::function<Ret(T...)> where sizeof...(T) == Number?


Solution

  • I suppose the following C++14 code can show you a way

    #include <utility>
    #include <functional>
    #include <type_traits>
    
    template <typename T, std::size_t>
    using use_type = T;
    
    template <typename...>
    struct bar;
    
    template <typename Ret, typename T, std::size_t ... Is>
    struct bar<Ret, T, std::index_sequence<Is...>>
     { std::function<Ret(use_type<T, Is>...)> func; };
    
    template <std::size_t N, typename Ret, typename T>
    struct foo : public bar<Ret, T, std::make_index_sequence<N>>
     { };
    
    int main ()
     {
       using T1 = std::function<void(int, int, int)>;
       using T2 = decltype(foo<3u, void, int>::func);
    
       static_assert( std::is_same<T1, T2>::value, "!" );
     }