Using a template struct such as many
below, it's possible to return a fixed set of possibly unmovable objects, and receive them using the c++17 structured binding (auto [a, b, c] = f();
declares the variables a
, b
and c
and assigns their value from f
returning for example a struct or tuple).
template<typename T1,typename T2,typename T3>
struct many {
T1 a;
T2 b;
T3 c;
};
// guide:
template<class T1, class T2, class T3>
many(T1, T2, T3) -> many<T1, T2, T3>;
auto f(){ return many{string(),5.7, unmovable()}; };
int main(){
auto [x,y,z] = f();
}
As explained in these two questions and answers (Do std::tuple and std::pair support aggregate initialization?
and especially the accepted answer by ecatmur, also Multiple return values (structured bindings) with unmovable types and guaranteed RVO in C++17), std::tuple
does not support aggregate initialization. That means that it can not be used to hold and return unmovable types. But a simple struct like many
can do this, which leads to the question:
Is it possible to create a variadic version of many
which works with any number of arguments?
Update: in a templated version of many
, will the following guide syntax be allowed?
template<typename Args...>
many(Args...) -> many<Args...>;
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…