0

I'm trying to define a toString helper method that should work either by using the << operator if available, or using a range-loop to print containers. I thought that C++11 and template magic would just sort of figure out what to use, but instead I'm getting the error "Redefinition of 'toString'".

    /** to string via o<<value operations */
    template<class T>
    inline static std::string toString(const T& value) {
        return (std::stringstream() << value).str();
    }

    /** to string via for each and tostring */
    template<class T>
    inline static std::string toString(const T& container) {
        std::stringstream stream;
        std::string delim = "";
        stream << "{";
        for (const auto& element : container) {
            stream << delim << toString(element);
            delim = ",";
        }
        stream << "}";
        return stream.str();
    }

I guess the definitions have to be separated somehow. It's possible to specialize the second template to vector, which works, but then it only works on vectors. So I tried to find a way to do it with traits and enable_if, which firstly I couldn't figure out, and secondly there doesn't seem to be a trait for 'supports range loop' or 'supports << operator'.

Ant6n
  • 1,887
  • 1
  • 20
  • 26
  • The [pretty printer](http://stackoverflow.com/q/4850473/596781) has to solve a very similar problem, and does so with a trait. – Kerrek SB Jul 01 '14 at 23:50
  • 1
    Look at [this answer](https://stackoverflow.com/a/9154394/241631) in the linked duplicate. – Praetorian Jul 02 '14 at 00:18
  • I gave a very minimal example to learn more about this and how a problem may solved this in C++11. The first duplicate solution has hundreds of lines to solve a similar problem and many others, and doesn't use C+11. The second one is hard to understand, not well explained, and doesn't refer to the code snippets in the question. – Ant6n Jul 02 '14 at 03:36
  • 1
    @Ant6n : Indeed, _some_ critical thinking is required. ;-] – ildjarn Jul 02 '14 at 20:07
  • Throwing oodles of code at people == requires critical thinking... – Ant6n Jul 02 '14 at 22:51
  • Ant6n : The answer @Praetorian linked to shows how to do it in two more lines of code than in your question. Had you read it, I think it would have been obvious. ;-] – ildjarn Jul 02 '14 at 23:32
  • Do "It" what? I did read the answer, I didn't understand it; it's not well explained. As I wrote before: "The second one is hard to understand, not well explained, and doesn't refer to the code snippets in the question." - I see no relationship between the code and the asked question. Essentially he's just throwing code at people. – Ant6n Jul 03 '14 at 00:12

0 Answers0