【发布时间】:2021-06-25 15:44:48
【问题描述】:
我正在尝试定义一个函数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++? IIRC C++20 让这变得更容易了。
-
如果它是非捕获的,则将默认设置为函数指针。或者完全不使用默认设置。
-
我不确定这是否算作重复,但this 是否回答了您的问题?
-
为什么要将 lambda 作为模板参数传递,而不是仅仅作为函数参数传递?
标签: c++ c++11 templates lambda template-argument-deduction