c++ - 我可以默认此 Transform 模板函数的返回类型吗?

标签 c++ templates

目前,要使用以下...

template< class ResultCollection, class Collection, typename Transformation >
ResultCollection Transform(const Collection& c, Transformation t)
{
    ResultCollection result(c.size());
    transform(c.begin(), c.end(), result.begin(), t);
    return result;
}

...您需要提供返回类型:

auto result = Transform< std::vector<int> >( someInputCollection, [] (SomeType& element) { return ElementToInt(element); });

是否可以默认模板参数,以便默认情况下您将获得一个 vector ,其中包含 lambda 返回的任何类型的元素?

我做到了:

template< class Collection, typename Transformation, class ResultCollection = std::vector< std::result_of_t<Transformation> > >
ResultCollection Transform(const Collection& c, Transformation t)
{
    ResultCollection result(c.size());
    transform(c.begin(), c.end(), result.begin(), t);
    return result;
}

但这给了我这个:

C2783: 'ResultCollection Transform(const Collection &,Transformation)' : could not deduce template argument for 'ResultCollection'

而且我不确定如何修复它。

最佳答案

您的代码有两个问题。第一个缺少 typename:

class ResultCollection = std::vector< typename std::iterator_traits<typename Collection::iterator>::value_type > 
                                      ^^^^^^^^                      ^^^^^^^^

但第二个是您传递的类型完全错误!如果您的 Transformation 实际上没有更改集合的值类型,那一切都很好,但如果它这样做了呢?

std::vector<char> collection;
auto result = Transform(collection, [](char c) { return std::string(c, 1); });

您需要生成的 vector 包含 Transformation 给出的类型:

class ResultCollection = std::vector<
    std::result_of_t<Transformation(decltype(*std::declval<Collection>().begin()))>
>

而且,顺便说一句,如果该结果类型不可默认构造怎么办?你假设它在这里:

ResultCollection result(c.size());

可能想改为这样做:

ResultCollection result;
result.reserve(c.size());
std::transform(c.begin(), c.end(), std::back_inserter(result), t);

或者真的:

ResultCollection result;
result.reserve(c.size());
for (const auto& elem : c) {
    result.push_back(t(elem));
}

关于c++ - 我可以默认此 Transform 模板函数的返回类型吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31866017/

相关文章:

c++ - 在不被 TCP 堆栈合并的情况下在单独的 TCP 段中发送数据

c++ - 使用 std::ios::sync_with_stdio(false) 可以比 scanf 和 printf 更快?

c++ - 是否有更适合键值数据结构的 QAbstractItemModel 类型类/接口(interface)?

c++ - 非模板函数接受模板消歧器

c++ - 在 C++ 中,如何使用模板函数作为 std::for_each 中的第三个参数?

c++ - printf() 是否像 cout 一样将其参数转换为字符串?

c++ - 如何理解vector pop_back的实现?

c++ - 如何禁用指针作为模板类型名

c++ - 如何为字符数组制作模板函数特化?

c++ - 错误 C2784 : Could not deduce template argument