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

匿名 (未验证) 提交于 2019-12-03 08:54:24

问题:

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!

回答1:

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


回答2:

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



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!