나중에 파생 클래스를 "확장"한다고 가정하고이 클래스를 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하려고 나는 다음 erorr 메시지를 얻을 :
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를 기본 클래스에 전달합니다. 왜이 기능이 작동하지 않습니까?
함수 인자 – BlamKiwi