Make type of vector arbitrary

Viewed 90

I'm currently implementing a simple stack in c++17, which has to have a toString-Method, that can deal among other types with std::vector as the template type.

My original problem was, that std::to_string can't accept vector's to I added a specialized implementation for vector's on top of my normal implementation:

template <class T> std::string SweCpp::Stack<T>::toString()
{
    std::string result = "SweCpp::Stack[";

    for (int a = 0; a < top + 1; a++)
    {
        T element = st[a];

        result += std::to_string(element);

        if (a != top) {
            result += ", ";
        }
    }
    result += "]";
    return result;
}


template <> std::string SweCpp::Stack<std::vector<double>>::toString() {
    std::string result = "SweCpp::Stack[";

    for (int a = 0; a < top + 1; a++)
    {
        std::vector<double> element = st[a];

        std::string vecAsString = "Vector{";
        for (double value : element) {
            vecAsString += std::to_string(value) + ",";
        }
        vecAsString += "}";

        result += vecAsString;
        if (a != top) {
            result += ", ";
        }
    }
    result += "]";
    return result;
}

The idea is to call to_string for every element of the vectors, and build a string like that. The problem is, that I can't figure out, how to make the double arbitrary. How can I implement it, so that I can pass any type of vector, e.g. std::vector<int> and std::vector<std::string>?

1 Answers

Something along these lines, perhaps:

template <typename T>
std::string MyToString(const T& val) {
  return std::to_string(val);
}

template <typename T>
std::string MyToString(const std::vector<T>& vec) {
  std::string vecAsString = "Vector{";
  for (const auto& value : vec) {
    vecAsString += MyToString(value) + ",";
  }
  vecAsString += "}";
  return vecAsString;
}

Now implement Stack<T>::toString() as in your first example, but call MyToString in place of std::to_string

Related