gpt4 book ai didi

使用 lambdas 推导 C++ 模板参数

转载 作者:搜寻专家 更新时间:2023-10-31 01:05:12 25 4
gpt4 key购买 nike

<分区>

我有以下模板声明

template<typename T>
void foo(function<void(T)> f){
// ...
};

但是当我这样调用它的时候

foo([](string s){ });
// visual studio 13 error message =>
// Error: void foo(std::function<void(_Type)>)' :
//could not deduce template argument for 'std::function<void(_Type)>'
//from 'main::<lambda_58b8897709e10f89bb5d042645824f66>

模板参数推导失败。为什么?如何解决?

我对可变参数模板有同样的问题

template<typename ... Tn>
void foo(function<void(Tn ...)> f){
// ...
};

int main() {
foo<string,bool>([](string s,bool b){ }); // Works
foo([](string s,bool b){ }); // Fails
}

但是如果我显式地转换 lambda 它会起作用 (!)

foo((function<void(string,bool)>) [](string s,bool b){ }); // Works

// Or even a simpler syntax with a macro
#define lmda_(a) (function<void a>)[&] a
foo( lmda_((string s, bool b)) { }); // Works (note the extra () )

为什么模板参数推导失败?以及如何解决?

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