Is there a way (without overloading) to call a function like this

GetValue("one");
//AND
std::string test("one");
GetValue(test);

The function is simply:

int GetValue(const std::string &MyString)
	{
		return MyMap[MyString];
	}

This overload does the job:

int GetValue(const char* MyString)
	{
		return MyMap[MyString];
	}

But that seems a little annoying to have to do. Any suggestions?

Thanks
Dave

Dani AI

Generated

raised a common API question and is right that a literal will bind through the usual conversions, but a few practical points were not discussed.

Using operator[] for the lookup will insert a default element when the key is missing. For read-only lookups prefer find or at so the map is not mutated accidentally:

auto it = MyMap.find(key);
if (it != MyMap.end()) return it->second;
return /* sentinel or error */;

For performance: implicitly creating a temporary std::string from a literal can allocate memory on some implementations; many standard libraries use small-string-optimizations that reduce that cost for short keys, but it should not be assumed. If allocation overhead matters, either add a lightweight overload for const char*, or in modern C++ accept std::string_view for zero-copy string-like parameters. std::string_view is non-owning, so its lifetime must outlive the lookup and it works best together with containers set up for heterogeneous lookup (transparent comparators / hashes) if avoiding a key copy is required.

Measure before changing the API: if the function is called rarely or keys are short, the simplest signature that expresses intent (const std::string&) is often the best. For design and reference details see the standard-library documentation for std::basic_string, std::basic_string_view, and associative containers (map/unordered_map) on cppreference:

These points keep the interface clear while addressing correctness (avoid accidental insertion) and giving options for optimization when needed.

Recommended Answers

All 2 Replies

The overload is not needed. As long as the function parameter is a const reference to string, you can pass a string constant and it will become a string object. Libraries usually have the overload to avoid the cost of constructing a new string object, but it is not required.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.