建议:尝试使用
// .........VVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV
static_loop<std::tuple_size_v<decltype(ab)>>([&](auto i) { std::get<i>(ab) = i; });
我的意思是...你不能使用ab
(作为值),在常量表达式中,因为ab
没有定义constexpr
.
而你无法定义它constexpr
因为它是使用初始化的std::ref()
那不是constexpr
.
但你不感兴趣ab
作为值来获取其类型的大小;你只对ab
类型;这样你就可以通过decltype(ab)
.
- 编辑 -
题外话建议。
代替static_loop()
,您可以使用基于的经典方法std::index_sequence
(以及模板折叠,从 C++17 开始可用)。
我的意思是...如果你定义一个run_1()
功能(与run_1_helper()
助手)如下
template <typename F, typename ... Ts, std::size_t ... Is>
void run_1_helper (F const & f, std::tuple<Ts...> & t, std::index_sequence<Is...> const)
{ (f(std::get<Is>(t), Is), ...); }
template <typename F, typename ... Ts>
void run_1 (F const & f, std::tuple<Ts...> & t)
{ run_1_helper(f, t, std::index_sequence_for<Ts...>{}); }
你可以写A
如下
struct A {
int a;
int b;
void run() {
auto ab = std::make_tuple(std::ref(a), std::ref(b));
run_1([](auto & v, auto i){ v = i; }, ab);
std::cout << a << " " << b << std::endl;
}
};
或者,也许更好,简单地使用std::apply()
, 如下
struct A {
int a;
int b;
void run() {
auto ab = std::make_tuple(std::ref(a), std::ref(b));
int i { -1 };
std::apply([&](auto & ... vs){ ((vs = ++i), ...); }, ab);
std::cout << a << " " << b << std::endl;
}
};