escouten
escouten

Reputation: 2973

How to avoid ambiguous constructor error when providing bool and double overloads

I'm building an class whose instances can represent multiple simple value types. It has an interface that looks roughly like this:

class value {

  public:

    value();
    explicit value( double value );
    explicit value( bool value );

 ...
}

I'm finding that I can't construct it in the way I was hoping because integer numbers (a very common use case) are considered ambiguous between bool and double.

value bool_value( true );   // OK
value pi_approx( 3.14159 ); // OK
value int_value( 42 );      // ERROR: ambiguous constructor

Is there any way to make this work without requiring callers to use a decimal point for numeric values or using explicit "make" static functions?

[EDIT]: This class represents values from a JSON parse tree, so the distinction between bool and number is significant and must be preserved.

Upvotes: 2

Views: 1453

Answers (2)

escouten
escouten

Reputation: 2973

It appears it's not possible to have the compiler automatically disambiguate the constructors in the way I had hoped.

I have worked around this by using factory methods instead:

class value {
  public:
    static value from_double( double value );
    static value from_int64( int64_t value );
    static value from_bool( bool value );
  ...
}

Upvotes: 2

ForEveR
ForEveR

Reputation: 55887

You should point, that it's double, or bool in this case. Something like

value int_value(static_cast<double>(42));

or simply write constructor, that should receive integer value.

Problem is, that compiler has two variants for construct object, one is convert integer to double and second is convert integer to bool, no one is worth than another, so, compiler cannot choose, without help to it.

Upvotes: 4

Related Questions