下面的lambda应该在编译时返回printf等的字符串格式化程序,但是它似乎没有按预期工作,我不能得到它。
演示
#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;
}
目前,它的产出是:
%llu
预期结果:
%hhu
1条答案
按热度按时间nnt7mjpx1#
decltype(std::get<Is>(dummy))
是T&
,对于可变std::tuple
,const T&
是std::tuple
。使用std::tuple_element_t
代替: