【发布时间】:2018-11-28 15:22:37
【问题描述】:
这就是我想做的;发布整个代码,因为它不会太长,也可以演示我要解决的具体任务。基本上,我需要一种按索引从参数包中迭代值的方法(索引部分很重要,即使在此示例中不需要它)。
#include <iostream>
#include <tuple>
#include <type_traits>
template <int First, int Last, typename Functor>
constexpr void static_for(Functor&& f)
{
if constexpr (First < Last)
{
f(std::integral_constant<int, First>{});
static_for<First + 1, Last, Functor>(std::forward<Functor>(f));
}
}
template <size_t index, typename... Args>
auto value_by_index(Args&&... args) noexcept {
return std::get<index>(std::forward_as_tuple(std::forward<Args>(args)...));
}
template <typename... ValueTypes>
void traverse(ValueTypes... values)
{
static_for<0, sizeof...(ValueTypes)>([&](int i) {
auto v = value_by_index<static_cast<size_t>(i), ValueTypes...>(values...);
std::cout << v << std::endl;
});
}
int main()
{
traverse(0.0f, 1, 3.33, "str");
return 0;
}
编译错误,当然是:
<source>:24:71: error: 'i' is not a constant expression
如果 lambda 可以有显式模板参数,i 就是这样一个参数,编译器在编译时就知道它是显而易见的。但这不是 lambda 的工作方式。
如果您想将其视为 XY 问题,我想我不需要在我的 static_for 中专门调用 lambda,但我确实需要调用一些可以访问参数包的代码traverse 的索引,如果 traverse 是成员函数,我需要访问它的 this。
【问题讨论】:
标签: c++ templates c++17 template-meta-programming constexpr