In C++, is it possible to generate a nested vector of depth (dimension) equal to a user defined input? For example, were a user to input an integer of value 2, one's program might create an object of type vector< vector< vector<int> > >. Obviously, there are numerous ways other ways one could easily achieve a similar behavior in C++, but I am purely interested as to whether or not the actual generation of an arbitrarily nested vector is possible. Initially, I thought this would be rather trivial, but my implementations all failed in rather curious ways.
#include<iostream>
#include<vector>
using namespace std;
template<typename A> void vec_print(vector<A> in){
cout << "{";
for(typename vector<A> :: iterator i = in.begin(); i != in.end(); ++i){
cout << *i << ", ";
}
cout << "}" << endl;
}
template<typename B> void vec_print(vector< vector<B> > in){
cout << "{";
for(typename vector< vector<B> > :: iterator i = in.begin(); i != in.end(); ++i){
vec_print(*i); cout << ", ";
}
cout << "}" << endl;
}
template<typename T> auto generate(unsigned int d){
if(d == 0){
vector<T> in;
return in;
}
return generate< vector<T> >(d - 1);
}
int main(){
unsigned int d = 0;
cin >> d;
vec_print(generate<int>(d));
return 0;
}
Initially, I thought this may work, though I was rather suspect of it on account of my understanding of how C++ compilers handle template functions. Using the g++ compiler with the --std=c++11 flag, prior to crashing, the g++ compiler recursively spewed errors informing me that function return type deduction was only available under the C++17 specification. Attempting to compile this program with the --std=c++17 flag resulted in no errors, but the compiler simply crashing. I suspect the compiler attempted to generate an infinite number of, or possibly 2^31, template functions, though I would have hoped for it to have handled this with an error warning of infinite template function generation as opposed to silently dying.
Aucun commentaire:
Enregistrer un commentaire