lundi 21 janvier 2019

How to convert a template type to string if it can be a string too?

I have class:

template <typename val_t>
class tracer_t : public base_tracer_t<val_t> {
    std::vector<std::string> m_trace;
public:
    virtual void push_fact(val_t fact) override {
        std::string str = "+ fact: " + to_string(fact);
        m_trace.push_back(std::move(str));
    }

    virtual void push_rule(const std::string &id, val_t val, bool tg) override {
        std::string str = "+ ";
        if (tg) { str += "target: "; }
        else { str += "rule: "; }
        str += id + " -> " + to_string(val);
        m_trace.push_back(std::move(str));
    }

    virtual void print() override {
        std::cout << "Stack trace: " << std::endl;
        for (auto it = m_trace.begin(); it != m_trace.end(); ++it) {
            std::cout << (*it) << std::endl;
        }
    }
private:
    std::string to_string(val_t val) {
        if (std::is_same<val_t, std::string>::value) {
            return (std::string)val;
        }
        return std::to_string(val);
    }
};

The problem is that it doesn't compile if val_t is std::string because of:

tracer.hpp:49: error: no matching function for call to ‘to_string(std::__cxx11::basic_string<char>&)’
         return std::to_string(val);
                ~~~~~~~~~~~~~~^~~~~

But I can't get how to resolve it. I tried to check type manually but error is in compile time,so it didn't help

Aucun commentaire:

Enregistrer un commentaire