|
| 1 | +#include<iostream> |
| 2 | +using namespace std; |
| 3 | + |
| 4 | +template<typename T> |
| 5 | +void print_type(){ std::cout<<__PRETTY_FUNCTION__<<'\n'; }//i.e. for debugging |
| 6 | + |
| 7 | +template<typename type,size_t size> |
| 8 | +struct array_adapter{ |
| 9 | + type data[size]; |
| 10 | +}; |
| 11 | + |
| 12 | +/************* testing runtime parameter deduction for template-argument ****************/ |
| 13 | +/*NOTES: |
| 14 | + 1) This technique basically allows us to use run-time parameters with compile-time |
| 15 | + 2) C++17 generic-lamba expression can also be used inside 'if' statement to make the function generic |
| 16 | +*/ |
| 17 | + template<size_t> |
| 18 | + void access_nth_tpp(size_t){}//i.e. base-case condition overload method |
| 19 | + |
| 20 | + template<size_t N,typename type,typename... types> |
| 21 | + void access_nth_tpp(const size_t& index){//i.e. tpp -> template parameter-pack |
| 22 | + if(index==N){//i.e. perform any operation inside if statement to make conversion |
| 23 | + |
| 24 | + constexpr size_t Compile_Time_Coverted=N;//i.e. index == N , means any operation u want to do with 'index', can also be done with 'N' |
| 25 | + |
| 26 | + array_adapter<type,N*N> temp;//i.e. declares an array of N*N size perfectly, since both parameters are compile-time |
| 27 | +// array_adapter<type,index>();i.e. gives error, since its a run-time parameter |
| 28 | + |
| 29 | + print_type<type>();//i.e. access nth-type of parameter-pack at run-time with this method |
| 30 | + return; |
| 31 | + } |
| 32 | + access_nth_tpp<N+1,types...>(index); |
| 33 | + } |
| 34 | + |
| 35 | + template<typename... types> |
| 36 | + void Get_Access(size_t index){ access_nth_tpp<0,types...>(index); } |
| 37 | + |
| 38 | +int main(){ |
| 39 | + int index=2; |
| 40 | + Get_Access<int,char,std::string,bool>(index);//i.e. prints respective type |
| 41 | + return 0; |
| 42 | +} |
0 commit comments