我遇到的问题是我有一个接受可变参数的函数。我想用它来打印
fmt
。我试图实现这一目标的方法就是加入他们。
我有我的加入功能:
template <typename RANGE, typename Projection = std::identity>
inline auto join(const RANGE& range, std::string_view sep, Projection&& proj = std::identity{}) {
auto joined = range
| std::views::transform([&proj](const auto& element) { return std::invoke(proj, element); })
| std::views::join_with(sep);
return std::ranges::to<std::string>(joined);
}
现在忽略
std::invoke
,因为它只是推导出身份,即std::format("{}");
如果我提供一个向量,它工作得很好,但是,如果我有一个可变参数函数,例如:
template<Args..>
foo(Args... args) {
std::string goo = std::format(
"Show me the keys: {}",
join(args..., ",")
);
}
它不起作用。我还尝试使用
std::forward_as_tuple
将我的 args
转换为 std::tuple
,但是,这没有帮助,因为操作数 |
不受 std::tuple
支持。
我有一个示例 here 显示带有
std::vector
和 std::tuple
(与可变参数结合使用)的情况
整个示例粘贴如下:
#include <iostream>
#include <string>
#include <vector>
#include <ranges>
#include <format>
#include <functional>
template <typename RANGE, typename Projection = std::identity>
inline auto join(const RANGE& range, std::string_view sep, Projection&& proj = std::identity{}) {
auto joined = range
| std::views::transform([&proj](const auto& element) { return std::invoke(proj, element); })
| std::views::join_with(sep);
return std::ranges::to<std::string>(joined);
}
template<typename... KEYS>
auto get(KEYS... keys) {
return std::forward_as_tuple(std::forward<KEYS>(keys)...);
}
int main() {
auto tuple_range = get("bla", "blas", "blaaaass");
auto vv = std::vector<std::string>{"bla", "blas", "blaass"};
std::string goo = std::format(
"Show me the keys: {}",
join(vv, ",")
);
std::cout << goo << std::endl;
return 0;
}
元组不是范围。用 C++ 术语来说,范围要求范围内的所有元素都属于同一类型。元组不是这样的,因此它们不能被任何范围机制操纵。