Search code examples
c++parameter-pack

Must I explicitly show the types in the parameter pack when instantiate a template?


I got a example to illustrate my question:

#include <utility>

class Foo {
 public:
  Foo(int i) {}
};

template<typename T, typename ...Args>
class Bar {
 public:
  T t;
  Bar(Args &&... args) : t(std::forward<Args>(args)...) {}
};

and if I want to instantiate this template:

Bar<Foo> foo(1);

the compiler throw an error:

no matching function for call to ‘Bar<Foo>::Bar(int)’

So I have to write to this:

Bar<Foo, int> foo(1);

This is annoying, especially if I got some classes which have a long list of parameters.

So is there any way I can get rid of explicitly showing the types in the parameter packs


Solution

  • If you want to constructor to forward, make that a template

    template<typename T>
    class Bar {
     public:
      T t;
      template<typename ...Args>
      Bar(Args &&... args) : t(std::forward<Args>(args)...) {}
    };
    

    We normally only care about the types of the arguments during the initialization of t, anyway.