6

So, I am writing a simple, templated search function for deque container. Here's the code:

 template <typename T> void searchInDequeFor(std::deque<T> Deque, T searchValue) { for(const auto & element : Deque) { if(Deque.empty()) { std::cout << "Deque is empty, nothing to search for..." << "\n"; } else if(element==searchValue) { std::cout << searchValue << " matches " << element << ", an element in the deque" << "\n"; } } } 

And, here's how I am calling the function in main:

 deque<string> myDeque={"apple", "banana", "pear", "blueberry"}; searchInDequeFor(myDeque,"pear"); 

This is the error I am getting:

candidate template ignored: deduced conflicting types for parameter 'T' ('std::__1::basic_string<char>' vs. 'const char *') 

Now, I've tested this function with integers, floats, doubles, etc., and it runs fine with those types, meaning my templating is working (for these types). This makes me wonder why I am getting this error when the function clearly knows that I am passing in a deque of type string and not of type const char *. Any help would be brilliant. Thanks!

2 Answers 2

12

To fix your function to allow for implicit conversions, make sure T only gets deduced from the first argument, not from the second.

template <typename T> struct identity { typedef T type; }; template <typename T> void searchInDequeFor(std::deque<T> Deque, typename identity<T>::type searchValue) 

This way, when you pass in a std::deque<std::string> and a const char *, the compiler will only be able to use the first argument for figuring out which T to use. Only after T has been fixed as std::string can the type of the second parameter be resolved, as std::string, and this will allow for implicit conversions from const char *.

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

1 Comment

This is pretty sweet! Thanks!
6

Well, std::string and const char* (<- this is what "pear" decays to when calling the function) are two different types you both want to deduce T from, just as the compiler says.

To fix the issue, call the function with the correct type:

searchInDequeFor(myDeque,std::string("pear")); 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.