テンプレートパラメーターを継承し、特定の基本メンバー関数のすべてのオーバーロードを一度にオーバーライドするテンプレートラッパークラスを作成しようとしています。次に例を示します。
#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 :: operator =を選択し、それらの引数をに転送するという考え方です。で構築する場合
gcc -std=c++11 -W -Wall -Wextra -pedantic test.cpp -lstdc++
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]
26w = std::string("???");
行目はthis_member_fnの宣言であり、15行目はthis_member_fnの宣言であるため、コンパイラーが考えるタイプfunc
(= std::string::operator=
)は期待していたタイプではないようです。
基本クラスのそれぞれを個別にoperator=
オーバーライドするのではなく、私と同じようにテンプレートを使用してこれを行う方法はありますか?operator=