Search code examples
c++templatesc++11variadic-templatesfunction-templates

How to modify each element of a parameter pack, and create a tuple from those?


I'm running into an issue with a variadic function template. I need to examine each element of a parameter pack, package the element, then stuff all the packaged elements into a tuple and return that. Here's the general idea of what I'd like to do (return types are just placeholders, not sure what they'd be):

template<typename A>
sometype func_helper(A a) {
    //examine a, depending on type, do different stuff with it.
    return modified_a;
}

template<typename... Args>
tuple<sometypes...> func(Args... args) {
    return make_tuple(func_helper...(args));
}

Any ideas?


Solution

  • You can use deduced return type. Sadly it has code reduplication:

    #include <iostream>
    #include <tuple>
    
    template<typename A>
    int func_helper(A ) {
        //examine a, depending on type, do different stuff with it.
        return 1;
    }
    
    char func_helper(double) {
        return 'A';
    }
    
    template<typename ...Args>
    auto func(Args... args) -> decltype(std::make_tuple(func_helper(args)...)) {
        return std::make_tuple(func_helper(args)...);
    }
    
    int main()
    {
        auto a = func(1, 3.4);
        std::cout << std::get<0>(a) << ' ' << std::get<1>(a) << '\n';
    }