4

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.

phuclv
  • 37,963
  • 15
  • 156
  • 475
unknown.prince
  • 710
  • 6
  • 19

3 Answers3

7

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

Marshall Clow
  • 15,972
  • 2
  • 29
  • 45
  • Is there a feature test macro for this? I can't find any at cppreference.com or the C++20 standard draft. The `__cpp_­lib_­variant` macros is still stuck at `201606L` according to https://eel.is/c++draft/version.syn#header:%3cversion%3e – Emile Cormier Dec 06 '20 at 20:37
2

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

phuclv
  • 37,963
  • 15
  • 156
  • 475
  • actually, in "real" code, I'm using QString and also std::variant has other members as well – unknown.prince Mar 14 '20 at 13:03
  • but regardless of your members, `"ad"s` will work to initialize the value to std::string – phuclv Mar 14 '20 at 13:08
  • 1
    @bluedragon QT has a [`QStringLiteral()`](https://doc.qt.io/qt-5/qstring.html#QStringLiteral) macro to create a `QString` from a string literal without making a copy of its data: `return p(QStringLiteral(u"ad"));` – Remy Lebeau Mar 14 '20 at 18:38
1

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.

KamilCuk
  • 120,984
  • 8
  • 59
  • 111