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

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

因此,我正在为双端队列容器编写一个简单的模板化搜索功能。这是代码:

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

而且,这是我在 main 中调用函数的方式:

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

这是我遇到的错误:

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

现在,我已经用整数、浮点数、双精度数等测试了这个函数,它在这些类型上运行良好,这意味着我的模板正在工作(对于这些类型)。这让我想知道为什么当函数清楚地知道我正在传递字符串类型而不是 const char * 类型的双端队列时我会收到此错误。任何帮助都会很棒。谢谢!

好吧,std::stringconst char*(<- 这是 "pear" 在调用函数时衰减的结果)是你们都想推断出的两种不同类型 T来自,正如编译器所说。

要解决此问题,请使用正确的类型调用函数:

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

要修复您的函数以允许隐式转换,请确保 T 仅从第一个参数推导出来,而不是从第二个参数推导出来。

template <typename T>
struct identity { typedef T type; };

template <typename T>
void searchInDequeFor(std::deque<T> Deque, typename identity<T>::type searchValue)

这样,当您传入 std::deque<std::string>const char * 时,编译器将只能使用第一个参数来确定要使用哪个 T。只有T固定为std::string后,才能解析第二个参数的类型,如std::string,这将允许隐式转换来自 const char *.