【发布时间】:2015-04-02 04:04:07
【问题描述】:
假设我有一个基类,以后可能会通过派生它来“扩展”,让我们称这个类为Base,扩展名为Derived。 类的模板签名是固定的,不能更改(即,我们不能更改类的模板参数)。 Derived 类的编写者对 Base 一无所知,只是它可能为其构造函数接受一些参数。
但是,最终派生类的调用者知道应该传递多少个参数。我该如何写这个Derived 扩展?这是我所拥有的:
struct Base
{
Base(int baseArg) {}
};
struct Derived : public Base
{
template <typename... Args>
Derived(Args&&... args, int derivedArg)
:
Base(std::forward<Args>(args)...)
{
}
};
当我尝试使用Derived d(1, 1); run this 时,我收到以下错误消息:
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
Derived 的构造函数应该有 2 个参数,使用第一个参数来构造自身并将第二个参数传递给基类。为什么这不起作用?
【问题讨论】:
-
将单个参数放在函数签名的首位
标签: c++ templates c++11 constructor variadic-templates