C ++错误:推导出参数'T'字符串与const char *的冲突类型 [英] C++ error: deduced conflicting types for parameter 'T' string vs const char *

查看:136
本文介绍了C ++错误:推导出参数'T'字符串与const char *的冲突类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以,我为deque容器编写了一个简单的,模板化的搜索函数。这里是代码:

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

调用main中的函数:

And, here's how I am calling the function in 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 *')

现在,我已经测试了这个函数的整数,浮点数,双精度等,它运行良好的类型,意思我的模板是工作(对于这些类型)。这让我想知道为什么我得到这个错误时,函数清楚地知道我传递的类型字符串的deque,而不是类型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!

推荐答案

好吧, std :: string $ c> const char * (< - 这是pear在调用函数时衰减)是两种不同类型

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.

要解决这个问题,请使用正确的函数来调用函数,如下所示: T 类型:

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

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

这篇关于C ++错误:推导出参数'T'字符串与const char *的冲突类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆