c++ - 如何将 lambda 传递给模板参数
问题描述
我正在尝试定义一个函数func()
,它返回一个std::string
.
template<typename T = std::string, template<typename> typename F = decltype([](const T &t){return t;})>
std::string func(const T &t){
F f;
return f(t);
}
如您所见,我要做的是传递一个 lambda 作为模板参数,以便我可以func()
像这样调用函数:
func<int, decltype([](int a){return std::to_string(a);})>(2);
另外,我为模板参数设置了默认值,以便我可以这样调用它:
func<>("abc");
但是,上面的代码给了我一个错误:
<source>:39:54: error: expected unqualified-id before 'decltype'
39 | template<typename T, template<typename> typename F = decltype([](const T &t){return t;})>
| ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
<source>:39:54: error: invalid default argument for a template template parameter
<source>:39:54: error: expected '>' before 'decltype'
顺便说一句,我的 C++ 版本是 C++11。
解决方案
在 C++11 中,您不能在未评估的上下文中使用 lambda 表达式,因此我认为您必须以不同的方式实现它。
C++20 添加了这个特性,所以这里有一个将在 C++20 中编译和运行的示例。
#include <iostream>
#include <string>
template<typename T = std::string, typename F = decltype([](const T &t)->std::string{return t;})>
std::string func(const T &t){
F f;
return f(t);
}
int main() {
// convert int to string
std::cout << func<int, decltype([](int a){return std::to_string(a);})>(2) << std::endl;
// take float parameter, but just ignore the parameter
std::cout << func<float, decltype([](float a){return "ignore the param";})>(2.2) << std::endl;
// default lambda
std::cout << func("abc") << std::endl;
return 0;
}
推荐阅读
- thymeleaf - 如何强制 Thymeleaf 显示具有空值的属性?
- c++ - CString::Mid() 是否有等效的 std::string?
- php - 使用 PHP 和 jQuery 的 Bootstrap 3 开放模式
- postgresql - 在 docker 的 pgadmin 中添加新的 postgres 服务器
- angular - Angular:自动进行版权检查
- java - AsyncTask 在哪里使用和在哪里不使用?
- core-data - 如果在 ItemView 中更新,则无法刷新 UI
- ruby-on-rails - 如何弄清楚如何修复资产:预编译错误
- amazon-web-services - jupyter notebook - 从命令行运行笔记本(并开始运行单元)并从浏览器访问它
- android - 如何观察基于用户提交按钮的 API 调用,同时从提交操作所必需的编辑文本中获取值?