Sign in to follow this  
Necrarch

Workaround for ambiguous call to overloaded function

Recommended Posts

Necrarch    122
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 this post


Link to post
Share on other sites
Oluseyi    2109
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 this post


Link to post
Share on other sites
Necrarch    122
Quote:
Original post by Oluseyi
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.


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

Share this post


Link to post
Share on other sites
Oluseyi    2109
Quote:
Original post by Necrarch
It'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!

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this