Prefer std::string in std::variant<bool, std::string> for const char *

Viewed 499

Consider the following code -

#include <variant>
#include <string>

int p(std::variant<bool, std::string> v) {
    return v.index();
}

int main() {
    return p("ad");
}

instead of choosing std::string, p will be instantiated with variant containing bool (I want std::string), well this can be fixed using explicitly specifying std::string but that is too much work , I tried providing different overloads but it doesn't seem to work.

3 Answers

This has been fixed in C++20. See P0608 for a discussion of this exact case.

You can use the string literal suffix s to create an std::string object directly

return p("ad"s);

If the suffix isn't available then you need to add using namespace std::literals, using namespace std::string_literals or using namespace std::literals::string_literals

That said, I've tried your code on Wandbox and p("ad") returns 1 for me

Such code:

#include <variant>
#include <string>

int p(std::variant<bool, std::string> v) {
    return v.index();
}

template<size_t N>
int p(const char (&s)[N]) {
    return p(std::string(s));
}

int main() {
    return p("ad");
}

returns 1.

Related