如何解决在函数中使用 std::array 使用“重载”lambdas
我希望在 C++20 中执行以下操作:
template <class... Ts>
struct overloaded : Ts... {
using Ts::operator( )...;
};
// Updated to work with C++17
#if (_cplusplus != 202002L) // check for C++17 or C++20
// Deduction guide,google `CTAD for aggregates` for more info
template <typename... Ts>
overloaded(Ts...) -> overloaded<Ts...>; // not needed before C++20
#endif
template <typename T,long int C = 0>
void emit(T const& data) {
auto emit = overloaded {
[&](const auto& value) {
mOs << value;
},[&](const uint8_t& value) {
mOs << std::showbase << (uint16_t)value;
},[&](const std::array<T,C>& value) {
for (auto& v : value) { // error: can't increment 0 size std::array
mOs << v;
}
},// bunch more lambdas
};
emit(data);
}
// invoked by
emit(1);
既然需要计数,如何捕获std::array?
如果不将 C 设置为零,所有其他 lambda 表达式都会失败。
可能不可能,但我想我会问。
解决方法
您可以使用 C++20 中引入的 lambdas 模板参数列表。 lambdas 参数不是 std::array<T,C>
而是 T
,而 T
是一些 std::array<S,C>
:
#include <iostream>
#include <array>
template <class... Ts>
struct overloaded : Ts... {
using Ts::operator( )...;
};
template <typename T>
void emit(T const& data) {
std::ostream& mOs = std::cout;
auto emit = overloaded {
[&](const auto& value) {
mOs << value;
},[&](const uint8_t& value) {
mOs << std::showbase << (uint16_t)value;
},[&]<typename S,size_t C>(const std::array<S,C>& value) {
for (auto& v : value) {
mOs << v;
}
},// bunch more lambdas
};
emit(data);
}
int main(){
// invoked by
std::array<int,42> x;
emit(x);
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。