Equal number of template and function params

  • A+
Category:Languages

Is there a way to generate a templated function where there is an equal number of template params and function params (of the same type)?

Like the following:

// template function: template<typename ... Args> void foo(const std::string& a, const std::string& b, ...) { /*...*/}  // example 1 foo<int>("one argument only");  // example 2 foo<int, double>("first argument", "second argument"); 

What if there is a default function param (not templated) (or multiple) which always exists?

template<typename ... Args> void foo(int i /* as default */, const std::string& a,                                  const std::string& b, ...)  { /*...*/} 

Would it even be possible to have, let's say the duplicate number of function arguments (calculated by the size of the template params)?

 


Is there a way to generate a templated function where there is an equal number of template params and function params (of the same type)?

Yes: it is (Edit: simplified following a Justin's suggestion; thanks!)

#include <string>  template <typename, typename T> using skip_first = T;  template <typename ... Args> void foo (skip_first<Args, std::string> ... as)  { }  int main()  {    foo<int>("one argument only");     foo<int, double>("first argument", "second argument");  } 

What if there is a default function param (or multiple)?

template<typename ... Args> void foo(int i /* as default */, const std::string& a,                                  const std::string& b, ...)  { /*...*/} 

If you want one (or more) preceding parameter(s) of different type(s), yes it's possible.

template <typename ... Args> void foo (int i, long j, skip_first<Args, std::string> ... as)  { } 

If you want a preceding parameter with a default value, no: isn't possible because a variadic list of parameter can't have a default value and because given a parameter with a default value all fallowing parameters have to have a default parameter.

Would it even be possible to have, let's say the duplicate number of function arguments (calculated by the size of the template params)?

I suppose you can multiply (repeat the unpack more times) the unpack part

template <typename ... Args> void foo (skip_first<Args, std::string> ... as1,           skip_first<Args, std::string> ... as2)  { } 

Obviously this solution works only if you want multiply the number of template argument for an integer number.

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: