Re: [Dev-C++] function overloading ambiguity
Open Source C & C++ IDE for Windows
Brought to you by:
claplace
|
From: Per W. <pw...@ia...> - 2004-04-30 23:17:12
|
If you write:
char *p =3D new char[20];
if (p) {
...
}
you don't expect any warnings about a conversion to bool, so obviously it
isn't any harder to make the same conversion when you send a char* as a
parameter.
The builtin data types already have their own conversion rules.
Had it been an object you had sent to your Test() functions, you
could have created your own conversion rules by writing:
class MyObj() {
char *m_s;
...
public:
operator const std::string() {
return std::string(m_str);
}
};
To make it possible to convert the object to a std::string object.
/Per W
On Fri, 30 Apr 2004, [ISO-8859-2] OROSZI Bal=E1zs wrote:
> Hi!
>
> I encountered a kind of "stupidity", which took me quite some time to
> debug in my original program. I had 3 functions, same name, they were
> overloaded.
>
> 1. function's parameter is: const string&
> 2. function's parameter is: int
> 3. function's parameter is: bool
>
> Here is a demonstration of my problem:
>
> --- Code ---
>
> #include <iostream>
> #include <string>
>
> using namespace std;
>
> void Test( const string& str )
> {
> =09cout << "Function called, type: 'string'" << endl;
> =09cout << " Value:" << str << endl;
> }
>
> void Test( int i )
> {
> =09cout << "Function called, type: 'int'" << endl;
> =09cout << " Value:" << i << endl;
> }
>
> void Test( bool b )
> {
> =09cout << "Function called, type: 'bool'" << endl;
> =09cout << " Value:" << b << endl;
> }
>
> int main()
> {
> =09Test( "This is some text" );
> =09Test( 12345 );
> =09Test( true );
>
> =09return 0;
> }
>
> --- Code End ---
>
> And this is the output:
>
> Function called, type: 'bool'
> Value:1
> Function called, type: 'int'
> Value:12345
> Function called, type: 'bool'
> Value:1
>
> A const char* was converted to a bool rather than to a const string&
> without a blink (i.e. without ANY warnings, even with -Wall and -W).
>
> Shouldn't at least the compiler spit out something, that "I'll convert
> your text to a bool"-like warning? :)
>
> I know, it sees char* as a pointer, and it seems easier for it to
> convert to bool, rather than to instanciate a string object, but why
> aren't there any *warnings* (about ambiguity)?
> It made me go crazy until I found this out...
> I later changed the first one to take const char* instead.
>
> Is it
|