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
Workaround for ambiguous call to overloaded function
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.
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.
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.
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..
Quote:Original post by NecrarchI'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:
It's not always desirable to include the huge stdlib.
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!
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement