variadic template parameter pack expanding for function calls

前端 未结 2 724
眼角桃花
眼角桃花 2020-12-01 12:44

I am looking for something like that:

template< typename T>  
void func(T t)
{
}

template< typename... Parms> 
void anyFunc( Parms... p)
{
    f         


        
相关标签:
2条回答
  • 2020-12-01 13:02

    Unfortunately, as you noticed, expanding a parameter pack is only valid in certain contexts where the parser expects a comma-separated list of entries – contexts where the comma is just a syntactic separator, not the comma operator. This is arguably a deficiency in the current text.

    An ugly workaround:

    func((some(p), 0)...);
    

    Do note that the evaluation order of function arguments, and thus the order of the some invocations, is unspecified, so you have to be careful with any side effects.

    0 讨论(0)
  • 2020-12-01 13:25

    How about a small helper class:

    template <typename Func, typename A, typename ...Args> struct Caller
    {
      static void call(Func & f, A && a, Args && ...args)
      {
        f(std::forward<A>(a));
        Caller<Func, Args...>::call(f, std::forward<Args>(args)...);
      }
    };
    
    template <typename Func, typename A> struct Caller<Func, A>
    {
      static void call(Func & f, A && a)
      {
        f(std::forward<A>(a));
      }
    };
    
    template <typename Func, typename ...Args>
    void Call(Func & f, Args && ...args)
    {
      Caller<Func, Args...>::call(f, std::forward<Args>(args)...);
    }
    

    Then you can put the following in your client code:

    void foo(A);
    Call(foo, a1, a2, a3);
    
    0 讨论(0)
提交回复
热议问题