我希望在 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);
}
关于c++ - 使用 'overloaded' lambdas 在函数中使用 std::array,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68613605/