c++ 按类型检索printf格式参数

xqkwcwgp  于 2023-07-01  发布在  其他
关注(0)|答案(1)|浏览(129)

下面的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
nnt7mjpx

nnt7mjpx1#

decltype(std::get<Is>(dummy))T&,对于可变std::tupleconst T&std::tuple。使用std::tuple_element_t代替:

([&]{ ret = Is; return std::same_as<T, std::tuple_element_t<Is, decltype(dummy)>>; }() || ...);

相关问题