Search code examples
c++overload-resolution

C++: avoid automatic conversion of string to bool in overloads


I want to create a set of methods that will output a value with special formatting based on its type. When I'm doing it this way, it looks so far so good:

static void printValue(std::ostringstream& out, int value) {
    out << value;
}

static void printValue(std::ostringstream& out, double value) {
    out << value;
}

static void printValue(std::ostringstream& out, const std::string& value) {
    out << "\"" << escapeString(value) << "\"";
}

Testing:

printValue(std::cout, 123);    // => 123
printValue(std::cout, 3.14);   // => 3.14
printValue(std::cout, "foo");  // => "foo"

However, as soon as I add bool overload:

static void printValue(std::ostringstream& out, bool value) {
    out << (value ? "true" : "false");
}

... things break, as bool-based overload seems to be used by default by add string invocations:

printValue(std::cout, 123);    // => 123
printValue(std::cout, 3.14);   // => 3.14
printValue(std::cout, true);   // => true
printValue(std::cout, "foo");  // => true <= !!!

Is there any way I can escape this automatic cast-to-bool and force compiler to choose a correct method for strings?


Solution

  • You could add an template overload that takes a reference to array of char of size N where N is a template parameter, and/or one that accepts a const char*.

    template <std::size_t N>
    static void printValue(sts::ostringstream& out, const char (&str)[N])
    {
        out << str;
    }