Suppose I have a base class that might later be "extended" by deriving from it, let's call this class Base
, and the extension Derived
. The template signature of the classes is fixed, and cannot be altered (ie. we cannot change the template arguments to the classes). The writer of the Derived
class knows nothing about Base
, only that it might take some arguments to its constructor.
However, the caller of the final derived class knows how many arguments should be passed. How can I write this Derived
extension? Here is what I have:
struct Base
{
Base(int baseArg) {}
};
struct Derived : public Base
{
template <typename... Args>
Derived(Args&&... args, int derivedArg)
:
Base(std::forward<Args>(args)...)
{
}
};
When I try to run this with Derived d(1, 1);
I get the following erorr message:
prog.cpp: In function 'int main()':
prog.cpp:19:16: error: no matching function for call to 'Derived::Derived(int, int)'
Derived d(1, 1);
^
prog.cpp:19:16: note: candidates are:
prog.cpp:11:2: note: template<class ... Args> Derived::Derived(Args&& ..., int)
Derived(Args&&... args, int myArg)
^
prog.cpp:11:2: note: template argument deduction/substitution failed:
prog.cpp:19:16: note: candidate expects 1 argument, 2 provided
Derived d(1, 1);
^
prog.cpp:8:8: note: constexpr Derived::Derived(const Derived&)
struct Derived : public Base
^
prog.cpp:8:8: note: candidate expects 1 argument, 2 provided
prog.cpp:8:8: note: constexpr Derived::Derived(Derived&&)
prog.cpp:8:8: note: candidate expects 1 argument, 2 provided
The constructor to Derived
should take 2 arguments, using the first to construct itself and passing the 2nd to the base class. Why doesn't this work?