2
#include <iostream>
#include <tuple>
#include <utility>

template <typename... T>
decltype(auto) getParameterPackVals(T&&... Args) noexcept {
    return std::get<1>(std::forward_as_tuple(std::forward<T>(Args)...));
}

int main() {
    std::cout << getParameterPackVals(2, 1.0, 2.0, 3.0, 4.0, 5.0) << std::endl;
    //print(1.0, "Hello", "This", "is", "An", "Honour");
    return 0;
}

This is my current code that works, with using 1 as a place holder for the variable. Although when I replace 1 with a variable (I tried both size_t and int in the arguments for getParameterPackVals) it does not work.

template <size_t V, typename... T>
decltype(auto) getParameterPackVals(V n, T&&... Args){
    return std::get<n>(std::forward_as_tuple(std::forward<T>(Args)...));
}

Is this a gap in my understanding of how the std::get function works? Is there a way to make this work as is or would I need to write an entirely new function?

4

1 回答 1

2

Wow this is a first I solved it on my own!

So while brainstorming I remembered that if I named a template argument such as size_t V I could pass it in with <V> when I called the argument. So I took V n out of the function arguments and called the function as getParameterPackVals<2>(1.0, 2.0, 3.0, 4.0, 5.0). The final code is now:

#include <iostream>
#include <tuple>
#include <utility>

template <size_t V, typename... T>
decltype(auto) getParameterPackVals(T&&... Args) noexcept{
    return std::get<V>(std::forward_as_tuple(std::forward<T>(Args)...));
}


int main() {
    std::cout << getParameterPackVals<2>(1.0, 2.0, 3.0, 4.0, 5.0) << std::endl;
    return 0;
}

I'll leave the question up incase anyone else comes upon a similar problem.

于 2021-02-23T16:24:23.963 回答