By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
445,918 Members | 2,246 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 445,918 IT Pros & Developers. It's quick & easy.

Selecting implicit type conversions?

P: n/a
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::operator=(int)
test.cc:26: A A::operator=(float)
test.cc:7: A& A::operator=(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.
Jul 19 '05 #1
Share this Question
Share on Google+
1 Reply


P: n/a

"Simon Leonard" <sl******@cs.ualberta.ca> wrote in message
news:4b*************************@posting.google.co m...
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::operator=(double) operator or
use explicit conversion.

--
Michael Kochetkov.
Jul 19 '05 #2

This discussion thread is closed

Replies have been disabled for this discussion.