Search code examples
c++templatestype-traits

C++ template recursively print a vector of vector using template


#include <any>
#include <iostream>
#include <string>
#include <sstream>
#include <vector>
using namespace std;

template<class T>
struct is_vector : std::false_type {};
template<class T>
inline constexpr bool is_vector_v = is_vector<T>::value;

template <typename T>
string VectorToString(const vector<T> &vec)
{
    string res = "[";
    int n = vec.size();
    for (size_t i=0; i<n; i++) {
        if constexpr(is_vector_v<T>) res += VectorToString(vec[i]);
        else res += std::to_string(vec[i]);
        if (i < n-1) res += ", ";
    }
    res += "]";
    return res;
}

int main( int argc, char** argv ) 
{        
    vector<int> a = {1,2,3};
    cout << VectorToString(a) << "\n";

    vector<vector<int>> b = {{1,2,3}, {4,5,6}, {7,8,9}};
    //cout << VectorToString(b);    

    vector<vector<vector<double>>> c = {{{1,2,3}, {4,5,6}}, {{7,8,9}}};
    //cout << VectorToString(c);    
    return 0;
}

I'm trying to make a print function that works with any vector type, like Python.

I wish to use template if possible, but not sure how. What should struct is_vector looks like to do this?

If a template solution is not possible, then I'd like to see any solution possible.


Solution

  • What should struct is_vector looks like to do this?

    It looks like what template partial specialization looks like

    template<class T>
    struct is_vector : std::false_type {};
    
    template<class T, class Alloc>
    struct is_vector<std::vector<T, Alloc>> : std::true_type {};
    

    Demo