busebd12
busebd12

Reputation: 1007

C++ error: deduced conflicting types for parameter 'T' string vs const char *

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!

Upvotes: 6

Views: 4724

Answers (2)

user743382
user743382

Reputation:

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 *.

Upvotes: 12

Baum mit Augen
Baum mit Augen

Reputation: 50063

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"));

Upvotes: 6

Related Questions