gpt4 book ai didi

c++ - 函数模板中返回类型的模板实参推导

转载 作者:太空宇宙 更新时间:2023-11-03 10:42:17 25 4
gpt4 key购买 nike

给定以下最小示例:

#include <algorithm>
#include <functional>
#include <iostream>
#include <iterator>
#include <list>
#include <set>
#include <vector>

template<typename ContainerOut, typename X, typename Y, typename ContainerIn>
ContainerOut Map( const ContainerIn& xs, const std::function<Y( const X& )>& f )
{
ContainerOut ys;
std::transform( begin( xs ), end( xs ), std::inserter( ys, end( ys ) ), f );
return ys;
}

struct Foo {
Foo( int val ) : val_( val ) {}
int val_;
};

std::set<int> FooValsToIntSet( const std::list<Foo>& foos )
{
//Map<std::set<int>, Foo, int>
return Map( foos, []( const Foo& foo )
{
return foo.val_;
} );
}

int main()
{
std::list<Foo> foos = { 1, 2, 2, 3 };
std::set<int> vals = FooValsToIntSet( foos );
for ( auto& v : vals )
std::cout << v << std::endl;
}

线

return Map( foos, []( const Foo& foo )

不被编译器接受 I tested .

如果我改为显式写出模板参数,它会起作用:

return Map<std::set<int>, Foo, int>( foos, []( const Foo& foo )

但我不明白为什么这是必要的。有没有办法避免这种冗长?

最佳答案

嗯,编译器无法推导 ContainerOut 类型——返回类型不参与类型推导。但是,您可以让编译器推断除返回类型之外的所有内容。作为旁注,至少在这种情况下,没有理由使用 std::function - 它只是增加了不必要的开销。

这样会更好:

template<typename ContainerOut, typename ContainerIn, typename F>
ContainerOut Map( const ContainerIn& xs, F&& f )
{
ContainerOut ys;
std::transform( begin( xs ), end( xs ), std::inserter( ys, end( ys ) ), f );
return ys;
}

然后你可以称它为

return Map<std::set<int>>( foos, []( const Foo& foo )
{
return foo.val_;
} );

关于c++ - 函数模板中返回类型的模板实参推导,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33083691/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com