gpt4 book ai didi

c++ - 函数模板、部分应用和模板参数推导

转载 作者:塔克拉玛干 更新时间:2023-11-03 07:48:26 25 4
gpt4 key购买 nike

我尝试让以下主要函数按预期进行编译和工作:

int main()
{
auto square = [](int x){ return x*x; };

typedef std::vector<int> Row;
typedef std::vector<Row> Mat;
Mat mat;
auto squareElements = Curry(Map<Row>, square);
Mat squaredMat = Map<Mat>(squareElements, mat);
}

现在我的补充代码是这样的:

#include <algorithm>
#include <functional>
#include <iterator>
#include <vector>

template <typename ContainerOut, typename ContainerIn, typename F>
ContainerOut Map( const F& f, const ContainerIn& xs )
{
ContainerOut ys;
// For performance reason one would use
// ys.reserve( xs.size() )
// and std::back_inserter instead of std::inserter
// if ys is a std::vector.
auto it = std::inserter( ys, end( ys ) );
std::transform( begin( xs ), end( xs ), it, f );
return ys;
}

template <typename Ret, typename Arg1, typename ...Args>
auto Curry( Ret f(Arg1, Args...), Arg1 arg ) -> std::function<Ret(Args...)>
{
return [=]( Args ...args ) { return f( arg, args... ); };
}

和它 does not compile .

知道如何让编译器推导出模板参数吗?

最佳答案

编译器错误说:

deduced conflicting types for parameter 'Arg1' ('const main()::<lambda(int)>&' and 'main()::<lambda(int)>')
auto squareElements = Curry(Map<Row, decltype(square)>, square);
^

将函数 Curry 更改为

template <typename Ret, typename Arg1, typename... Args>
auto Curry(Ret (*f)(const Arg1&, const Args&...), const Arg1& arg ) -> std::function<Ret(Args...)>
{
return [=]( Args... args ) { return f( arg, args... ); };
}

或将函数 Map 更改为:

template <typename Container, typename F>
Container Map(F f, Container xs );

这将编译!

看看我的代码:Ideone

关于c++ - 函数模板、部分应用和模板参数推导,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33706740/

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