1

When trying to compare two strings, one wrapped in a boost::variant type, it works only half of the time. If my boost::variant contains string, int, double, and bool, it doesn't work (it gives me this error: libc++abi.dylib: terminating with uncaught exception of type boost::wrapexcept<boost::bad_get>: boost::bad_get: failed value get using boost::get Abort trap: 6). But if my boost::variant contains just a string and an int, it works just fine! This makes no sense to me. If you have any idea why this is happening, and how to fix it, please let me know.

// variant_equality.cpp

#include <boost/variant.hpp>
#include <string>
#include <iostream>

// doesn't work: #define varied_type boost::variant<std::string, int, double, bool>

// does work: #define varied_type boost::variant<std::string, int>

bool variant_equal(varied_type v, std::string normal) {
    try {
        return boost::get<std::string>(v) == normal;
    }

    catch (boost::bad_get) {
        return false;
    }
}

int main() {
    varied_type bar = "foo";
    std::cout << variant_equal(bar, "foo") << std::endl;
    return 0;
}
Caspian Ahlberg
  • 934
  • 10
  • 19
  • 1
    I'm going to take a stab and say that `"foo"` gets converted to a bool before it gets shoved into the variant. Presumably `varied_type bar = std::string("foo");` would always work. – Bill Lynch Aug 23 '20 at 17:45
  • `bool` is a better match than `std::string` given a pointer. See https://stackoverflow.com/questions/4111495/why-is-there-an-implicit-type-conversion-from-pointers-to-bool-in-c – cigien Aug 23 '20 at 17:47
  • @cigien why is the string a pointer here? It's not assigned to a memory location so how could that be? – Caspian Ahlberg Aug 23 '20 at 18:18
  • 3
    There's no string. `"foo"` is a `char const[4]`. If you want a string, do `"foo"s`. – cigien Aug 23 '20 at 18:23

0 Answers0