C++高级模板编程: 将tuple作为可变模板参数调用

需求描述

有一个外部可变模板参数的接口,比如C++20std::format

需要将其封装成比较便捷的操作符调用方式,比如

auto s = "{} {}" % T(a, b, c, ...);

如何实现?

需求分析

  1. 首先这里需要一个T的可变模板参数函数,返回结果是一个固定类型的对象,不如就用标准库的 std::tuple
  2. 然后还需要重载 %操作符
template<typename Tuple>
std::string operator%(std::string_view fmt, Tuple&& tpl)

如何实现

  1. 首先需要实现一个T函数
template<typename ...Ts>
std::tuple<Ts...> T(Ts&& ...ts)
{
    return std::make_tuple(std::forward<Ts>(ts)...);
}
  1. 然后要对外部变参模板函数做一下封装
template<typename Tuple, size_t... Indices>
std::string format(std::string_view fmt, Tuple&& tpl, std::index_sequence<Indices...>)
{
    return std::format(fmt, std::get<Indices>(std::forward<Tuple>(tpl))...);
}
  1. 最后再定义操作符重载
template<typename Tuple>
std::string operator%(std::string_view fmt, Tuple&& tpl)
{
    return format(fmt, std::forward<Tuple>(tpl),
        std::make_index_sequence<std::tuple_size_v<std::remove_reference_t<Tuple>>>{});
}

验证结果

int main(int, char**)
{
    using namespace std::string_literals;
    
    std::cout << "name={} age={}" % T("逗神大人"s, 18) << std::endl;

    return 0;
}

输出结果:
在这里插入图片描述

是不是很炫 ^_^

其他类似的外部变参模板接口都可以这么封装,重点在第二步的Tuple -> 变参模板

你可能感兴趣的:(C++,STL,C++,模板,c++,开发语言)