# Workaround for ambiguous call to overloaded function

## Recommended Posts

Hello, I'm programming in C++. I have made a class which manages data records. I want to be able to retrieve a data record by calling Class->GetItem. I want to be able to call GetItem by specifying a key-string or an integer value.
CExampleClass
{
public:

CExampleClass(void);
~CExampleClass(void);

CDataRecord * GetItem(int index);
CDataRecord * GetItem(const char* key);
}

There's a problem with this. THIS WORKS: a = GetItem(1); b = GetItem("Test"); THIS FAILS: a = GetItem(0); The compiler says: Ambiguous call to overloaded function. I understand why this is. That 0 argument could be an int or a null-pointer. It could be solved by calling the function as follows: a = GetItem( (int)0 ); b = GetItem( 1 ); c = GetItem( "Test" ); I don't want the users of my lib to need to explicitly type the 0 to int. Is there no way so that GetItem(0) works withou type it? Regards, Necrarch

##### Share on other sites
CDataRecord * GetItem(const std::string & key);

I should mention that returning a raw pointer may be dangerous, as it spreads out the possibilities of memory management. Consider either using a policy-based smart/shared pointer or returning a sequence iterator.

##### Share on other sites
Quote:
 Original post by OluseyiCDataRecord * GetItem(const std::string & key);I should mention that returning a raw pointer may be dangerous, as it spreads out the possibilities of memory management. Consider either using a policy-based smart/shared pointer or returning a sequence iterator.

It's not always desirable to include the huge stdlib. It isn't desireable in my case anyway..

##### Share on other sites
Quote:
 Original post by NecrarchIt's not always desirable to include the huge stdlib.
I'm sure you mean <string>. If you have legitimate constraints preventing you from using the STL, you can write a simple proxy string class that accepts literals, and returns const char * just for this purpose. Something like this:
class ProxyString{public:  ProxyString(const char * str)  {    length = strlen(str);    text = new char[length];    strncpy(str, text, length);  }  operator const char * () const  {    return text;  }protected:  ProxyString() {}private:  size_t length;  char * text;};

You can then do the following:

CDataRecord * GetItem(const ProxyString & key);

Voila!

## Create an account

Register a new account

• ### Forum Statistics

• Total Topics
628381
• Total Posts
2982360

• 10
• 9
• 15
• 24
• 11