I'm trying to create a template wrapper class which inherits from its template parameter and which overrides all of the overloads of a particular base member function in one go. Here's an example:
#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;
}
The idea is that the template for Wrapper<T>::operator=
will select the correct T::operator= at compile-time based on its argument, and then forward those arguments on. If I build with
gcc -std=c++11 -W -Wall -Wextra -pedantic test.cpp -lstdc++
I get the following complaints from gcc:
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]
Line 26 is w = std::string("???");
and line 15 is the declaration of this_member_fn, so it seems that the type the compiler thinks func
(=std::string::operator=
) has is not the one it was expecting.
Is there a way to do this using a templated operator=
like I am, rather than overriding each operator=
in the base class individually?