默认模板类Lambda
Default template class lambda
,假设您有一个模板函数,该功能可能采用"收集",可能是"转换" lambda:
template<typename Collection, typename Transform>
void DoIt(const Collection &c, Transform transform)
{
for(auto &item: c)
{
std::cout << transform(item);
}
}
,但我想要一个lambda的默认转换,它只是返回对其参数的引用。如果收集:: value_type支持&lt;&lt;进入流,您只需致电
DoIt(collection);
但是,如果没有,您可以致电:
DoIt(collection, [](const collection::value_type &item) { item.ToString();});
可能最简单的答案是超载该函数,一个调用另一个呼叫:
template<typename Collection, typename Transform>
void DoIt(const Collection &c, Transform transform)
{
for(auto &item: c)
{
std::cout << transform(item);
}
}
template<typename Collection>
void DoIt(const Collection &c)
{
DoIt(c, [](auto &item) -> decltype(item) { return item; });
}
,或者,如果您真的只需要一个模板,则需要一个像功能的类别,只需通过其参数。
namespace std_compat {
struct identity
{
template<typename T>
constexpr T&& operator()(T&& obj) const noexcept
{ return std::forward<T>(obj); }
using is_transparent = void;
};
}
template<typename Collection, typename Transform = std_compat::identity>
void DoIt(const Collection &c, Transform transform = {})
{
for(auto &item: c)
{
std::cout << transform(item);
}
}
这也允许用户执行诸如DoIt<decltype(c), std::negate<>>(c);
之类的事情。这似乎不是特别好。
注意std::identity
出现在C 20。
// Function object that returns a reference to x
struct SelfReference
{
template<class T>
auto operator()(T& x) const -> T&
{
return x;
}
};
// default template argument selects SelfReference
// also note default argument
template<typename Collection, typename Transform = SelfReference>
void DoIt(const Collection &c, Transform transform = Transform())
{
for(auto &item: c)
{
std::cout << transform(item);
}
}
相关文章:
- 在未显式传递参数时默认使用 lambda 的用户输入
- 处于默认参数位置的 Lambda 无法访问好友成员。这是编译器错误吗?
- 变量不能在 lambda 中隐式捕获,并且没有使用 switch 语句指定捕获默认值
- 是否可以使用默认泛型参数在C++中定义 lambda?
- C++14 及更高版本是否允许 Lambda 函数的默认参数?如果是这样,怎么办?
- 使用默认参数从 lambda 调用最少数量的参数
- 可以使用默认参数复制包含 lambda 的 std::函数吗?
- lambda 的默认捕获是什么?
- 默认引用与命名的 lambda 捕获
- 在默认初始值设定项中使用 lambda 与使用成员函数
- 如何编写具有默认参数的lambda的通用函数
- 未评估上下文中的默认模板参数和 lambda:错误还是功能?
- 默认模板类Lambda
- C++14 lambda 的默认参数类型推导,具体取决于前面的参数
- 如何将 lambda 用作模板参数,C++ 中的默认值
- 默认函数对象值作为要使用lambda调用的函数参数
- 模板,lambda作为每个实例化的唯一默认参数
- 当另一个调用 lambda 使用默认捕获时,lambda 的闭包可能会被破坏吗?
- 将具有默认参数的lambda函数复制到变量
- 在C++11中使用lambda默认值捕获或引用捕获的缺点