英文:
Retrieving printf format parameter by type
问题
以下是翻译好的部分:
这个lambda函数应该在编译时返回类似printf等的字符串格式化器,但似乎无法按预期工作,我无法理解它的工作原理。
当前输出:
%llu
预期结果:
%hhu
#include <array>
#include <string_view>
#include <iostream>
int main() {
using T = unsigned char;
constexpr std::string_view fmt = [&]() -> std::string_view {
std::tuple<char, unsigned char, short, unsigned short, int,
unsigned int, long, unsigned long, long long, unsigned long long> dummy;
constexpr std::size_t map_size = std::tuple_size_v<decltype(dummy)>;
constexpr std::size_t idx = [&](auto... Is)(std::index_sequence<Is...>){
std::size_t ret = 0;
([&]{ ret = Is; return std::same_as<T, decltype(std::get<Is>(dummy))>(); }() || ...);
return ret;
}(std::make_index_sequence<map_size>{});
return std::array<std::string_view, map_size>{"%hhd", "%hhu", "%hd", "%hu", "%d", "%u", "%ld", "%lu", "%lld", "%llu"}[idx];
}();
std::cout << fmt << std::endl;
}
英文:
The following lambda is supposed to return the string formatter for printf and alike at compiletime, however it doesn't seem to work as intended and I can't get behind it.
#include <array>
#include <string_view>
#include <iostream>
int main() {
using T = unsigned char;
constexpr std::string_view fmt = [&]() -> std::string_view {
std::tuple<char, unsigned char, short, unsigned short, int,
unsigned int, long, unsigned long, long long, unsigned long long> dummy;
constexpr std::size_t map_size = std::tuple_size_v<decltype(dummy)>;
constexpr std::size_t idx = [&]<std::size_t... Is>(std::index_sequence<Is...>){
std::size_t ret = 0;
([&]{ ret = Is; return std::same_as<T, decltype(std::get<Is>(dummy))>; }() || ...);
return ret;
}(std::make_index_sequence<map_size>{});
return std::array<std::string_view, map_size>{ "%hhd", "%hhu", "%hd", "%hu", "%d", "%u", "%ld", "%lu", "%lld", "%llu" }[idx];
}();
std::cout << fmt << std::endl;
}
Currently it outputs:
%llu
Expected result:
%hhu
答案1
得分: 4
decltype(std::get<Is>(dummy))
在可变的 std::tuple
中为 T&
,在不可变的 std::tuple
中为 const T&
。请使用 std::tuple_element_t
替代:
([&]{ ret = Is; return std::same_as<T, std::tuple_element_t<Is, decltype(dummy)>>; }() || ...);
英文:
decltype(std::get<Is>(dummy))
is T&
for a mutable std::tuple
, const T&
for immutable std::tuple
. Use std::tuple_element_t
instead:
([&]{ ret = Is; return std::same_as<T, std::tuple_element_t<Is, decltype(dummy)>>; }() || ...);
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论