How do I prevent implict conversion to boost::variant types with multiple types of integers?

StackOverflow https://stackoverflow.com/questions/23687534

  •  23-07-2023
  •  | 
  •  

Question

I am trying to work with boost::variant and am running into a bit of a problem with the way I am using it. I was hoping someone could shed some light on the situation.

I have created a boost::variant and templatized it with both an int and an unsigned int. When I assign a numeric value, (ie. 4) to the variant, I would expect the compiler to complain since plain old 4 cannot have it's type inferred unambiguously. How does this even compile?! How does the compiler choose the type?

Is there a way to make the compiler complain about these sorts of things?

#include <stdint.h>
#include <boost/variant.hpp>
#include <boost/scoped_ptr.hpp>
#include <cxxabi.h>

struct MyComplexType
{
    int myInt;
    uint32_t myUint;
};

int main()
{
    boost::variant< MyComplexType, int, uint32_t, float, std::string> myAmbiguousVar;

    myAmbiguousVar = 4; // <- ?? My compiler chooses this to be an int

    int status;
    boost::scoped_ptr<char> pDemangled(__cxxabiv1::__cxa_demangle(myAmbiguousVar.type().name(), 0, 0, &status));
    std::cout << std::string(pDemangled.get()) << std::endl;
}
Était-ce utile?

La solution

The type of a numeric literal is not ambiguous, and is largely implicitly convertible. In short, 4 is an int, and 4U is an unsigned int. Unless your compiler has a specific warning for such things, it's unlikely you will get it to warn.

Autres conseils

Based on Michael Urman's response, I wanted to fill this answer in a bit more completely.

The C++ standard states the following(2.14.2.2):

The type of an integer literal is the first of the corresponding list in Table 6 in which its value can be represented.

Table 6 lists the the order of integer literals as roughly, int, unsigned int, long int, unsigned long int, ... etc

Based on the above, that is why the compiler is assigning boost::variant an int type.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top