템플릿 매개 변수에서 상속되고 특정 기본 멤버 함수의 오버로드를 모두 무시하는 템플릿 래퍼 클래스를 만들려고합니다. 다음 예는 다음과 같습니다 기본 멤버 함수의 모든 오버로드를 단일 템플릿 멤버 함수에서 재정의하고 전달할 수 있습니까?
#include <cassert>
#include <string>
#include <utility>
template <class T>
class Wrapper: public T {
public:
template <typename... Args>
Wrapper<T>& operator=(Args&&... args) {
return this_member_fn(&T::operator=, std::forward<Args>(args)...);
}
private:
template <typename... Args>
Wrapper<T>& this_member_fn(T& (T::*func)(Args...), Args&&... args) {
(this->*func)(std::forward<Args>(args)...);
return *this;
}
};
int main(int, char**) {
Wrapper<std::string> w;
const std::string s("!!!");
w = s;
assert(w == s);
w = std::string("???");
assert(w == std::string("???"));
return 0;
}
아이디어는 Wrapper<T>::operator=
의 템플릿은 앞으로 다음 해당 인수를 인수에 따라 컴파일시 = 올바른 T :: 연산자를 선택한 것입니다. (
test.cpp: In instantiation of ‘Wrapper<T>& Wrapper<T>::operator=(Args&& ...) [with Args = {std::basic_string<char, std::char_traits<char>, std::allocator<char> >}; T = std::basic_string<char>]’:
test.cpp:26:24: required from here
test.cpp:10:69: error: no matching function for call to ‘Wrapper<std::basic_string<char> >::this_member_fn(<unresolved overloaded function type>, std::basic_string<char>)’
test.cpp:10:69: note: candidate is:
test.cpp:15:15: note: Wrapper<T>& Wrapper<T>::this_member_fn(T& (T::*)(Args ...), Args&& ...) [with Args = {std::basic_string<char, std::char_traits<char>, std::allocator<char> >}; T = std::basic_string<char>]
test.cpp:15:15: note: no known conversion for argument 1 from ‘<unresolved overloaded function type>’ to ‘std::basic_string<char>& (std::basic_string<char>::*)(std::basic_string<char>)’
test.cpp: In member function ‘Wrapper<T>& Wrapper<T>::operator=(Args&& ...) [with Args = {std::basic_string<char, std::char_traits<char>, std::allocator<char> >}; T = std::basic_string<char>]’:
test.cpp:11:3: warning: control reaches end of non-void function [-Wreturn-type]
라인 (26) w = std::string("???");
과 라인 (15) this_member_fn의 선언, 그래서 컴파일러가 func
을 생각하는 유형 보인다 : 나는
gcc -std=c++11 -W -Wall -Wextra -pedantic test.cpp -lstdc++
빌드하면 나는 GCC에서 다음 불만을 얻을 = std::string::operator=
)가 기대했던 것이 아닙니다.
기본 클래스의 각 operator=
을 개별적으로 재정의하는 것이 아니라 내가 템플릿을 사용하여 operator=
을 사용하는 방법이 있습니까?
어쨌든 당신은 'int'에서 상속받을 수 없습니다 :) +1 –