In C ++ 11, variable templates allow you to call a function with any number of arguments, and an ellipsis operator ...allows this variational function to do something with each of these arguments, even if it is something not the same for each argument:
template<typename... Types>
void dummy(Types... ts){}
template<typename... Numerics>
void increment5(Numerics&... ns){
dummy(ns+=5 ...);
}
int main(){
int i = 0;
float f = 1.1;
std::valarray<int> vi = {1,2,3};
increment5(i,f,vi);
cout
<<i<<endl
<<f<<endl
<<vi[0]<<' '<<vi[1]<<' '<<vi[2]<<endl;
}
If we define a heterogeneous array of values (a list of different types of numbers), we want to be able to do the same (to be able to add a number to each of its elements). But we must store the elements as a tuple.
template<typename... Numerics>
class HeterogeneousValueArray{
private:
tuple<Numerics...> inner;
public:
HeterogeneousValueArray(Numerics... ns): inner(ns...) {}
};
template<typename... Numerics>
HeterogeneousValueArray<Numerics...> HeterogeneousValueArray(Numerics... ns){
return HeterogeneousValueArray<Numerics...>(ns);
}
increment5 , . , , . 5, .
, , , . .
template<typename... Numerics>
void increment5(HeterogeneousValueArray<Numerics...>& hva){
increment5(hva.inner... );
}
.
template<typename... Numerics>
void increment5(HeterogeneousValueArray<Numerics...>& hva){
dummy((hva.inner+5)... );
}
, .
, " , ", , . , (?), ? ... ++ 14?