473,887 Members | 2,290 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Ambiguity by making overloaded operator function-const - why?

Hi,
I have the following code and trouble with ambiguity due to operator
overloading..

The code is also at http://paste.nn-d.de/441

snip>>

#include <iostream>
#include <string>
#include <map>

using namespace std;
class ConfigItem;
typedef map<wstring, ConfigItemConfi gMap;

class ConfigItem {

public:
ConfigItem() { type=NONE; s[0]=0; }
ConfigItem(cons t wchar_t *str) {
type=STRING;
wcscpy(s, str);
}
operator const wchar_t*() const {
return s;
}
wchar_t operator[](int pos) const {
return (operator const wchar_t*())[pos];
}
ConfigItem& operator[](const wchar_t *option) {
return operator[](wstring(option ));
}
ConfigItem& operator[](const wstring &option) {
switch (type) {
case MAP: return (*cm)[option];
default: return *this;
}
}

private:
enum {
NONE,
INT,
STRING,
MAP,
} type;

wchar_t s[512];
ConfigMap *cm;
};
int main() {
if (wchar_t(Config Item()[0]) == L'\0')
cout << "works as expected";

return 0;
}

<<snap

If I compile it using g++ 4.1.2, I get:

test.cpp: In function 'int main()':
test.cpp:53: error: ISO C++ says that these are ambiguous, even though
the worst conversion for the first is better than the worst conversion
for the second:
test.cpp:24: note: candidate 1: wchar_t ConfigItem::ope rator[](int)
const
test.cpp:32: note: candidate 2: ConfigItem& ConfigItem::ope rator[]
(const std::wstring&)
test.cpp:53: error: ISO C++ says that these are ambiguous, even though
the worst conversion for the first is better than the worst conversion
for the second:
test.cpp:24: note: candidate 1: wchar_t ConfigItem::ope rator[](int)
const
test.cpp:29: note: candidate 2: ConfigItem& ConfigItem::ope rator[]
(const wchar_t*)

On which path does ISO C++/the compiler deduct the second
candidates?? Now for the really (to me) weird part:

If I remove the function const from wchar_t operator[](int pos) const
so it reads

wchar_t operator[](int pos) {

above code works as expected and no ambiguity error is shown, the
following does also work

const wchar_t operator[](const int pos) {
It is just the function const that provokes the ambiguity - why?

Many thx for an insightful reply, I spent hours on this and don't
really have a clue, why making an overloaded operator function-const
opens paths to the ambiguity shown.

Btw, this is not the full code, just the minimal part to make the
mistake happen

Thanks much,
Christian Müller
Jun 1 '08 #1
4 3401

<ab********@gma il.coma écrit dans le message de news:
ef************* *************** **...legroups .com...
Hi,
I have the following code and trouble with ambiguity due to operator
overloading..

The code is also at http://paste.nn-d.de/441

snip>>

#include <iostream>
#include <string>
#include <map>

using namespace std;
class ConfigItem;
typedef map<wstring, ConfigItemConfi gMap;

class ConfigItem {

public:
ConfigItem() { type=NONE; s[0]=0; }
ConfigItem(cons t wchar_t *str) {
type=STRING;
wcscpy(s, str);
}
operator const wchar_t*() const {
return s;
}
wchar_t operator[](int pos) const {
return (operator const wchar_t*())[pos];
}
ConfigItem& operator[](const wchar_t *option) {
return operator[](wstring(option ));
}
ConfigItem& operator[](const wstring &option) {
switch (type) {
case MAP: return (*cm)[option];
default: return *this;
}
}

private:
enum {
NONE,
INT,
STRING,
MAP,
} type;

wchar_t s[512];
ConfigMap *cm;
};
int main() {
if (wchar_t(Config Item()[0]) == L'\0')
cout << "works as expected";

return 0;
}

<<snap

If I compile it using g++ 4.1.2, I get:

test.cpp: In function 'int main()':
test.cpp:53: error: ISO C++ says that these are ambiguous, even though
the worst conversion for the first is better than the worst conversion
for the second:
test.cpp:24: note: candidate 1: wchar_t ConfigItem::ope rator[](int)
const
test.cpp:32: note: candidate 2: ConfigItem& ConfigItem::ope rator[]
(const std::wstring&)
test.cpp:53: error: ISO C++ says that these are ambiguous, even though
the worst conversion for the first is better than the worst conversion
for the second:
test.cpp:24: note: candidate 1: wchar_t ConfigItem::ope rator[](int)
const
test.cpp:29: note: candidate 2: ConfigItem& ConfigItem::ope rator[]
(const wchar_t*)

On which path does ISO C++/the compiler deduct the second
candidates?? Now for the really (to me) weird part:

If I remove the function const from wchar_t operator[](int pos) const
so it reads

wchar_t operator[](int pos) {

above code works as expected and no ambiguity error is shown, the
following does also work

const wchar_t operator[](const int pos) {
It is just the function const that provokes the ambiguity - why?

Many thx for an insightful reply, I spent hours on this and don't
really have a clue, why making an overloaded operator function-const
opens paths to the ambiguity shown.

Btw, this is not the full code, just the minimal part to make the
mistake happen

Thanks much,
Christian Müller

ok first try this :

if (wchar_t(Config Item()[1]) == L'\0') // 0 changed by 1
cout << "works as expected";

you gonna see that it work. That is because using 0 could be interpreted as
a NULL pointer and that is the reason the compiler is considering the
function with a wchar_t *.

you can do :

int zero = 0;
if (wchar_t(Config Item()[zero]) == L'\0') // 0 changed by 1
cout << "works as expected";

than it will work.

Now for the const thing.
First, the return value is never used in argument deduction, so adding a
const to the return value does not change anything, but it does if you make
the function const.
This should work fine

const ConfigItem c;
if (wchar_t(c[0]) == L'\0')
cout << "works as expected";

cause c is const and therefore no ambiguity here since the function is
const.


Jun 2 '08 #2
ok first try this :
>
if (wchar_t(Config Item()[1]) == L'\0') // 0 changed by 1
cout << "works as expected";

you gonna see that it work. That is because using 0 could be interpreted as
a NULL pointer and that is the reason the compiler is considering the
function with a wchar_t *.

you can do :

int zero = 0;
if (wchar_t(Config Item()[zero]) == L'\0') // 0 changed by 1
cout << "works as expected";

than it will work.
Thanks for your answer, but at least the first part is bogus, first
statement is not true - it does not matter if i use 0 or 1, the
ambiguity is even present if I do:

if (wchar_t(Config Item()[int(0)]) == L'\0') // explicit cast to int
cout << "works as expected";

Now for the const thing.
First, the return value is never used in argument deduction, so adding a
const to the return value does not change anything, but it does if you make
the function const.

This should work fine

const ConfigItem c;
if (wchar_t(c[0]) == L'\0')
cout << "works as expected";

cause c is const and therefore no ambiguity here since the function is
const.
Ok this works, but I was under the impression that making a function
const just makes the compiler enforce my intention to not change any
values outside of the scope of this function.. you say it does make a
difference, but in what way. After all, I am allowed to call the
const function from a non-const ConfigItem. So why is it ambiguous?

Regards and thx,
Christian
Jun 2 '08 #3
On Jun 1, 10:38 pm, abendst...@gmai l.com wrote:
I have the following code and trouble with ambiguity due to
operator overloading..
The code is also athttp://paste.nn-d.de/441
snip>>
#include <iostream>
#include <string>
#include <map>
using namespace std;
class ConfigItem;
typedef map<wstring, ConfigItemConfi gMap;
class ConfigItem {
public:
ConfigItem() { type=NONE; s[0]=0; }
ConfigItem(cons t wchar_t *str) {
type=STRING;
wcscpy(s, str);
}
operator const wchar_t*() const {
return s;
}
wchar_t operator[](int pos) const {
return (operator const wchar_t*())[pos];
}

ConfigItem& operator[](const wchar_t *option) {
return operator[](wstring(option ));
}
ConfigItem& operator[](const wstring &option) {
switch (type) {
case MAP: return (*cm)[option];
default: return *this;
}
}
private:
enum {
NONE,
INT,
STRING,
MAP,
} type;
wchar_t s[512];
ConfigMap *cm;
};
int main() {
if (wchar_t(Config Item()[0]) == L'\0')
cout << "works as expected";
return 0;
}
<<snap
If I compile it using g++ 4.1.2, I get:

test.cpp: In function 'int main()':
test.cpp:53: error: ISO C++ says that these are ambiguous, even though
the worst conversion for the first is better than the worst conversion
for the second:
test.cpp:24: note: candidate 1: wchar_t ConfigItem::ope rator[](int)
const
test.cpp:32: note: candidate 2: ConfigItem& ConfigItem::ope rator[]
(const std::wstring&)
test.cpp:53: error: ISO C++ says that these are ambiguous, even though
the worst conversion for the first is better than the worst conversion
for the second:
test.cpp:24: note: candidate 1: wchar_t ConfigItem::ope rator[](int)
const
test.cpp:29: note: candidate 2: ConfigItem& ConfigItem::ope rator[]
(const wchar_t*)
On which path does ISO C++/the compiler deduct the second
candidates??
For the operator[], the compiler considers two arguments, the
object on which it is going to be called (the argument which
becomes the this pointer), and the index argument. In your
expression, ConfigItem()[0], you have a (non-const) ConfigItem,
and a constant integral expression evaluating to 0. Both
operator[]( int ) const and operator[]( wchar_t* ) can be
called. For the first argument, the second is the better match,
because the first requires a qualifier conversion. For the
second argument, the first is a better match, because it is an
exact match. The result is that the call is ambiguous.
Now for the really (to me) weird part:
If I remove the function const from wchar_t operator[](int
pos) const so it reads
wchar_t operator[](int pos) {
above code works as expected and no ambiguity error is shown,
Yes. Because now, you have a better match for the second
argument, and the first two are equal (both exact matches).
the following does also work
const wchar_t operator[](const int pos) {
This is the same as the above.
It is just the function const that provokes the ambiguity - why?
Because it means that calling the function on a non-const object
requires a qualifier conversion.
Many thx for an insightful reply, I spent hours on this and
don't really have a clue, why making an overloaded operator
function-const opens paths to the ambiguity shown.
It *is* sometimes surprising. But frankly, I'd wonder about so
many overloads. What does [] mean on an object of your class?
Off hand, I'd say that if you have [] whose return type differs
in more than just const, then you have operator overload abuse:
if there's a natural meaning for [], then that will exclusively
determine the return type, and if there's not, then you
shouldn't use [].

--
James Kanze (GABI Software) email:ja******* **@gmail.com
Conseils en informatique orientée objet/
Beratung in objektorientier ter Datenverarbeitu ng
9 place Sémard, 78210 St.-Cyr-l'École, France, +33 (0)1 30 23 00 34
Jun 2 '08 #4
On Jun 2, 4:44 am, abendst...@gmai l.com wrote:
ok first try this :
if (wchar_t(Config Item()[1]) == L'\0') // 0 changed by 1
cout << "works as expected";
you gonna see that it work. That is because using 0 could be interpretedas
a NULL pointer and that is the reason the compiler is considering the
function with a wchar_t *.
you can do :
int zero = 0;
if (wchar_t(Config Item()[zero]) == L'\0') // 0 changed by 1
cout << "works as expected";
than it will work.
Thanks for your answer, but at least the first part is bogus, first
statement is not true - it does not matter if i use 0 or 1, the
ambiguity is even present if I do:
if (wchar_t(Config Item()[int(0)]) == L'\0') // explicit cast to int
cout << "works as expected";
Which still has the 0. Use 1 instead of 0, and the ambiguity
disappears. Use anything but a constant integral expression,
and the ambiguity disappears.

--
James Kanze (GABI Software) email:ja******* **@gmail.com
Conseils en informatique orientée objet/
Beratung in objektorientier ter Datenverarbeitu ng
9 place Sémard, 78210 St.-Cyr-l'École, France, +33 (0)1 30 23 00 34
Jun 2 '08 #5

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

8
17888
by: Nitin Bhardwaj | last post by:
Thanx in advance for the response... I wanna enquire ( as it is asked many a times in Interviews that i face as an Engg PostGraduate ) about the overloading capability of the C++ Language. Why can't the = (assignment) operator be overloaded as a friend function ? I work in VS 6.0 ( Win2000 ) as when i referred the MSDN documen'n it said the following :
20
37416
by: Brad Eck | last post by:
"The only operators that cannot be overloaded are :: (scope resolution), . (member selection), and .* (member selection through pointer to function). Quoting from Stroustrup's 3rd edition of _The C++ Programming Language_, section 11.2 (page 263), these three operators 'take a name, rather than a value, as their second operand and provide the primary means of referring to members. Allowing them to be overloaded would lead to subtleties.'"...
5
13163
by: IvD² | last post by:
During a project I ran into trouble when using multiple inheritance. I was able to resolve the problem, but was unable to really understand the reasons for the error. Here is a short example of the problem: class BaseA { ...
5
5023
by: Gianni Mariani | last post by:
Can anyone enligten me why I get the "ambiguous overload" error from the code below: friendop.cpp: In function `int main()': friendop.cpp:36: ambiguous overload for `std::basic_ostream<char, std::char_traits<char> >& << Thing&' operator friendop.cpp:27: candidates are: std::basic_ostream<_CharT, _Traits>& operator<<(std::basic_ostream<_CharT, _Traits>&, const Thing&) friendop.cpp:14: std::basic_ostream<_CharT, _Traits>&...
4
1626
by: masood.iqbal | last post by:
Please help me with this doubt that I have regarding overloaded operators. Sometimes they are member functions and sometimes they are friends (e.g. see the code snippet from Stroustrup, Second Edition that I have posted to comp.sources.d). How do we decide which is more appropriate? Why are the overloaded "<<" and ">>" operators always friends? Also, what is an appropriate application for the overloaded function call operator?
11
1881
by: Alexander Stippler | last post by:
Hi I have already posted and discussed the following problems once, but despite really helpful hints I did not get any further with my problem (I at least learned, first to exactly consider why something does not work instead of immediately searching for work arounds) . I have the following code resulting in an ambiguity: -------------------------------------------------------- template <typename Impl> class Vector {};
85
3326
by: masood.iqbal | last post by:
I know that this topic may inflame the "C language Taleban", but is there any prospect of some of the neat features of C++ getting incorporated in C? No I am not talking out the OO stuff. I am talking about the non-OO stuff, that seems to be handled much more elegantly in C++, as compared to C. For example new & delete, references, consts, declaring variables just before use etc. I am asking this question with a vested interest. I...
9
8186
by: rohits123 | last post by:
I have an overload delete operator as below ////////////////////////////////// void operator delete(void* mem,int head_type) { mmHead local_Head = CPRMemory::GetMemoryHead(head_type); mmFree(&local_Head,(char *)mem); CPRMemory::SetMemoryHeadAs(local_Head,head_type); } ///////////////////// void* operator new(size_t sz, int head_Type) {
13
5055
by: Tristan Wibberley | last post by:
Hi I've got implementing overloaded operator new and delete pretty much down. Just got to meet the alignment requirements of the class on which the operator is overloaded. But how does one implement operator new/delete I can't see a way to indicate, on delete, how many objects must be destroyed (or how big the space is) - alternatively I can't figure out what are the alignment requirements so that the implementation, after calling my...
2
2122
by: subramanian100in | last post by:
overloaded operator=() -------------------------------- overloaded assignment operator should be a non-static MEMBER function of a class. This ensures that the first operand is an lvalue. If the overloaded assignment operator function is allowed to be a non- member function then we may be able to write the following: Suppose we have a class Test for which operator+() is defined, suppose we have
0
9957
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
11173
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10771
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10877
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
10434
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
7988
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6011
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4633
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
4239
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.