Login | Register   
LinkedIn
Google+
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


advertisement
 

Blocking Undesirable Object Copying and Implicit Conversions-4 : Page 4

C++ doesn't offer a direct mechanism for blocking undesirable copying or preventing implicit conversion of arguments. However, with some code tweaks you can work around these problems.


advertisement

Blocking Undesirable Conversion
In 2006, I discussed a private case of disabling undesirable conversions from bool. While the "indirect conversion" idiom works satisfactorily with Boolean types, it doesn't solve the general problem of implicit conversions among arithmetic types. Consider:


void func(long double){/**/}
int main()
{
 long double n=0;
 int x=0;
 func(n);//OK, perfect match of argument and parameter
 func(x);//OK, implicit int to long double conversion
}

The second func() call compiles successfully, although it may well be buggy. In C++03, there's no simple way to exclude integral types from being silently promoted to floating-point types when an argument doesn't match perfectly the parameter specified in the signature. If int to long double conversion is undesirable, you can prevent it by declaring additional overloads of func()that will intercept arguments of the wrong types. Notice that these "interceptors" should only be declared, not implemented:




void func(long double) 
{}
//list of "interceptors"
void func(int);
void func(bool);
void func(short);
void func(char);

After adding the interceptors, if the wrong type of argument is passed to func(), you'll get a linkage error:


int main()
{
 long double n=0;
 int x=0;
 func(n);//OK, perfect match of argument and parameter
 func(x);//linkage error: void func(int) undefined
}

This technique has one limitation: your arguments must match the parameter exactly. If you pass an argument of type float or double instead of long double, the compiler will consider the call ambiguous and issue an error message:


float n=0;
func(n);//error, ambiguous call

The compiler can't decide which overloaded version of func()to call because there's no perfect match between the argument's type and any of the parameters of the overload set. Therefore, this technique is mostly useful when a perfect match between arguments and parameters are required.



Danny Kalev is a certified system analyst and software engineer specializing in C++. He was a member of the C++ standards committee between 1997 and 2000 and has since been involved informally in the C++0x standardization process. He is the author of "The ANSI/ISO Professional C++ Programmer's Handbook" and "The Informit C++ Reference Guide: Techniques, Insight, and Practical Advice on C++."
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap