1

I'm running these two lines of code to add to a map later on:

o.add("-i", 800,             "int option");  
o.add("-w", "'switch on' option (no third parameter)");

To add them i'm using my two add functions defined as:

template<class T>
void add(std::string name, T value, std::string desc);
template<class T>
void add(std::string name, std::string desc);

The first one works fine, and returns the values I want, but if I add the second one, I get the error:

error: no matching function for call to ‘Opt::add(const char [3], const char [40])’

My question is why it's using my strings in the first one properly, and my strings in the second are being thought of as const char arrays.

Thank you in advance.

2 Answers 2

1

Since you're not using the template argument in your second overload, remove it:

template<class T>
void add(std::string name, T value, std::string desc);

void add(std::string name, std::string desc);

A working sample can be found here.

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks alot, for some reason I thought I was using T later on in my function, but it turns out I'm not. For education's sake though, why exactly would that cause my strings to be detected as char arrays?
Because they are char arrays. The compiler saw two overloads of add, one with three parameters, and one with a non-automatically deducible template parameter. Since the call didn't match either one of the overloads, it showed you the actual types with which you were trying to call the function. And in C++, unlike in C# and Java, string literals have char array type, not std::string type, although they are automatically convertible to std::string, because std::string has a non-explicit constructor that takes a char array.
@Classtronaut, Yes, it shows you the type you pass in. It can still be converted to a different type, as happens in the first example.
1

The error message is weird, but to use the second overload you need to explicitly specify the template argument (since there's no way to automatically deduce it):

o.add<T>("-w", "'switch on' option (no third parameter)"); 

Or, if you don't actually need the template parameter in this case, just make it a non-template method.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.