I have used the following code which work well for printing a simple std::vector with printContainer().
I want now to extend it for nested containers with printContainerV2()
I have tried using template to determine if the type is a stl container but it does not seem to be the way to do it.
#include <iostream>
#include <iterator>
#include <vector>
template <typename Iter, typename Cont>
bool isLast(Iter iter, const Cont& cont)
{
return (iter != cont.end()) && (next(iter) == cont.end());
}
template <typename T>
struct is_cont {
static const bool value = false;
};
template <typename T,typename Alloc>
struct is_cont<std::vector<T,Alloc> > {
static const bool value = true;
};
template <typename T>
std::string printContainer(T const& container)
{
std::string str = "{";
for (auto it = std::begin(container); it != std::end(container); ++ it)
if (isLast(it, container))
str = str + std::to_string(*it) + "}";
else
str = str + std::to_string(*it) + ",";
return str;
}
/*
template <typename T>
std::string printContainerV2(T const& container)
{
std::string str = "{";
for (auto it = std::begin(container); it != std::end(container); ++ it)
if (isLast(it, container))
if (is_cont<decltype(*it)>::value == true)
str = str + printContainer(*it);
else
str = str + std::to_string(*it) + "}";
else
if (is_cont<decltype(*it))>::value == true)
str = str + printContainer(*it);
else
str = str + std::to_string(*it) + ",";
return str;
}
*/
int main()
{
std::vector<int> A({2,3,6,8});
std::vector<std::vector<int>> M(2,A);
M[1][0] ++;
std::cout << is_cont<decltype(A)>::value << std::endl; // returns true !
for (auto it = std::begin(M); it != std::end(M); ++ it)
{
std::cout << printContainer(*it) << std::endl; // works well std::vector<int>
std::cout << is_cont<decltype(*it)>::value << std::endl; // return false :(
}
// Want to use this for printing a std::vector<std::vector<int>>
// std::cout << printContainerV2(M) << std::endl; // not working !
}
For the moment it is ok if the code works only for std::vector type and up to one nested level (std::vector< std::vector>>). I am not sure it can be generic without efforts...