Selecting implicit type conversions?

S

Simon Leonard

I'm developing an API that I want be as user friendly as possible. My
problem is that there are functions that can take many optional
parameters (of various type) and I want to be able to specify them in
an arbitrary order (forget about default values). I think I figured
out a simple way of doing this but I still have one little annoyance
(actually it's more a curiosity than an annoyance).

Here's a simplified example. In the real thing I'm using va_arg for
the variable length argument list in the function f (hence the union
instead of a template).

#include <iostream>
using namespace std;

enum{PARAMETER1, PARAMETER2};

class A{
public:

union Value{
int int_value;
float float_value;
};

int ID;
Value value;

A(int i){ID = i;}

// PARAMETER1 is of type int
A operator = (int i){
if(ID == PARAMETER1) // sanity check
value.int_value = i;
return *this;
}

// PARAMETER2 is of type float
A operator = (float f){
if(ID == PARAMETER2) // sanity check
value.float_value = f;
return *this;
}
};

void f(A a){
if(a.ID == PARAMETER1)
cout<<a.value.int_value<<endl;
if(a.ID == PARAMETER2)
cout<<a.value.float_value<<endl;
}

A parameter1(PARAMETER1);
A parameter2(PARAMETER2);

int main(){

f(parameter1=1);
f(parameter2=2.52); // LINE 1
f(parameter2=2.52f); // LINE 2

return 1;
}

LINE 1 doesn't compile. It tries to figure out which '=' to use
test.cc: In function `int main()':
test.cc:47: ambiguous overload for `A& = double' operator
test.cc:21: candidates are: A A::eek:perator=(int)
test.cc:26: A A::eek:perator=(float)
test.cc:7: A& A::eek:perator=(const A&)

LINE 2 works fine. Howerver I wonder if it is possible to achieve the
same result without the constant suffixe (or an explicit conversion to
float).

Can I have the compiler to figure that it's better to convert a double
to a float than an int?

Any thoughts?

Thanks.
 
M

Michael Kochetkov

Simon Leonard said:
I'm developing an API that I want be as user friendly as possible. My
You propably may want to consider voice or gesture interface indeed :).

[...]
Can I have the compiler to figure that it's better to convert a double
to a float than an int?
I am afraid not, you cannot. You are to add A::eek:perator=(double) operator or
use explicit conversion.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,146
Messages
2,570,832
Members
47,374
Latest member
anuragag27

Latest Threads

Top