For unit testing, I wrote a class ScopeSet which changes the values of variables in the current scope, and at the end of the scope the original values are set back.
Usage example:
int i = 1;
double d = 2.;
{
auto _ = ScopeSet( i, 10, d, 20. );
assert( i == 10 );
assert( d == 20. );
}
assert( i == 1 );
assert( d == 2. );
I have finished the class, except for the deduction guides.
ScopeSet takes a variable number of variable-value pairs.
So far I have written the deduction guides by hand for up to three pairs
template< typename T0, typename U0 > ScopeSet( T0 &, U0 ) -> ScopeSet< T0 >;
template< typename T0, typename U0, typename T1, typename U1 > ScopeSet( T0 &, U0, T1 &, U1 ) -> ScopeSet< T0, T1 >;
template< typename T0, typename U0, typename T1, typename U1, typename T2, typename U2 > ScopeSet( T0 &, U0, T1 &, U1, T2 &, U2 ) -> ScopeSet< T0, T1, T2 >;
My question is, how can I write a deduction guide which works for a variable number of pairs?
You could start with a class to store a reference to a single variable, that assigns a new value to the variable at construction and restores the old value on destruction:
This
ScopePairis usable as-is if you only need to handle a single variable.The
ScopeSetcan then consist of any number of suchScopePairs by recursively inheriting from aScopeSetwhere one pair of arguments are picked off at a time:Demo
The above makes
ScopeSet( i, 10, d, 20. );into aScopeSet<int, int, double, double>which is much easier than to shave off every other type.If you absolutely must have a one
intand onedoubleyou could add a specialization forScopeSet<ScopeSetTypes<Ts...>>that inherits fromScopeSet<Ts...>. Using the deduction guide will then makeScopeSet( i, 10, d, 20. );into aScopeSet<ScopeSetTypes<int, double>>:Demo