繁体   English   中英

候选模板被忽略:无法推断模板参数“U”

[英]candidate template ignored: couldn't infer template argument 'U'

我正在尝试创建一个Vec类,它包含返回新Vec对象的方法map 我希望map方法可以返回不同的类型(如 Javascript 的 map 函数)。

发现错误:

main.cpp:31:13: error: no matching member function for call to 'map'
    numbers.map([](int &item)
    ~~~~~~~~^~~

main.cpp:18:12: note: candidate template ignored: couldn't infer template argument 'U'
    Vec<U> map(Lambda lambda)

这是我的代码:

#include <iostream>
#include <vector>
#include <algorithm>
#include <iterator>

template <typename T>
class Vec
{
public:
    std::vector<T> value;

    Vec(std::vector<T> vector)
    {
        value = vector;
    }

    template <typename Lambda, typename U>
    Vec<U> map(Lambda lambda)
    {
        std::vector<U> updatedValue;
        std::transform(value.begin(), value.end(), std::back_inserter(updatedValue), lambda);
        Vec<U> UpdatedVector(updatedValue);
        return UpdatedVector;
    }
};

int main()
{
    Vec<int> numbers({10, 20, 30, 40, 50});

    Vec<std::string> new_numbers = numbers.map([](auto &item)
                                               { return "new value is string"; });

    // Value of the 'new_numbers.value' should be {"new value is string", "new value is string", "new value is string", "new value is string", "new value is string"}

    return 0;
}

在 C++ 中,您不能针对返回类型专门化函数,函数模板也是如此。 要专注于模板值,您需要明确地专门化您的函数模板返回值,如下所示:

#include <iostream>
#include <vector>
#include <algorithm>
#include <iterator>
#include <string>

template <typename T>
class Vec
{
public:
    std::vector<T> value;

    Vec(std::vector<T> vector)
    {
        value = vector;
    }

    // I reversed the order of the template arguments here
    template <typename U, typename Lambda>
    Vec<U> map(Lambda lambda)
    {
        std::vector<U> updatedValue;
        std::transform(value.begin(), value.end(), std::back_inserter(updatedValue), lambda);
        Vec<U> UpdatedVector(updatedValue);
        return UpdatedVector;
    }

    auto& values() const noexcept
    {
        return value;
    }
};

int main()
{
    Vec<int> numbers({ 10, 20, 30, 40, 50 });

    // NOTE the explicit target type to convert to in map function template call
    Vec<std::string> new_numbers = numbers.map<std::string>([](const auto& item) 
    { 
        return std::to_string(item); 
    });

    for (const auto& value : new_numbers.values())
    {
        std::cout << value << "\n";
    }

    return 0;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM