mardi 25 juillet 2017

C++11: how to write a template function that works like get

I know that in c++11, the get<> template function works with std::tuple to get the indexed value of the tuple, this is resolved at compile time.

But my requirement is to have a template function called get<> but receives a parameter pack, so the code should be like below:

#include<iostream>
using namespace std;
template<typename Head, typename ... Tail>
auto get(size_t index, Head&& t, Tail&&...tail){
    return get(index-1, tail...);
}
template<typename Head, typename ... Tail>
Head get<0>(Head&& t, Tail&&...tail){
    return t;
}
int main(){
    cout<<get(3,"abc",'x',27,"hello")<<endl;
    cout<<get(2,"abc",'x',28,"hello")<<endl;
    return 0;
}

Well it doesn't compile, for sure, as I don't know how to write such a "get" template function. I wish the main function will run and print as below:

hello
28

So my question: how to implement this "get" template as I mentioned above? Thanks!

Aucun commentaire:

Enregistrer un commentaire