Boost logo

Boost :

From: Eric Friedman (ebf_at_[hidden])
Date: 2004-01-13 02:59:17


Drazen DOTLIC wrote:

> Hello,
>
> While trying the following code (vc7.1)
>
> boost::variant<std::string, long, bool> v1 = "Test";
>
> I noticed that v1 was initialized to be bool and not string.

Yes, this at first seems very confusing. But it (unfortuantely?) does
mirror standard overloading rules, as I will show below.

[snip]
> String implementation that comes with vc7.1 does not have constructor
> that accepts const char[] (that's type of "Test") so compiler decides
> that conversion to bool is better match than conversion to const char*
> and then initializing string - is this correct?

I am no expert in the standard, but I believe this is what's happening.

Try the following example program to compare:

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

   void f(const std::string& s) {
     std::cout << s << '\n'; // never called
   }

   void f(bool b) {
     std::cout << b << '\n';
   }

   int main() {
     f("Test");
   }

Compiling the above program with g++ 3.2.3 and running yields output: 1

> If this is standard behavior, is there a way to overcome it in variant
> library itself - should I want this even (in other words, any
> undesirable side effects)?

I am not sure what is the best decision here. On the one hand such
behavior seems totally unexpected. But on the other hand, it matches the
standard function overloading rules. If variant does not follow these
rules, then what rules should it follow?

Anyhow, unless there is an obvious, simple change to be made (?),
resolution of this issue (if any) will need to be postponed until a
subsequent (post-1.31) Boost release.

Eric


Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk