我正在阅读 Advanced C++ Metaprogramming 这本书,我在第2.2.3节遇到了一段代码。 (第49页)没有编译(我当前的编译器是Visual Studio 2013)。分配时会出现错误,但书中说明了作业" ok:它最终调用basic_inner :: operator = "。我错过了什么吗?
template <typename X, typename T>
struct basic_inner
{
template <typename T2>
basic_inner& operator=(const basic_inner<X, T2>&)
{
// do something...
return *this;
}
};
template <typename T>
struct outer
{
template <typename X>
struct inner : public basic_inner<X, T>
{
inner& operator=(const basic_inner<X, T> &that)
{
static_cast<basic_inner<X, T>&>(*this) = that;
return *this;
}
};
};
template <>
struct outer<int>
{
template <typename X>
struct inner : public basic_inner<X, int>
{
inner& operator=(const basic_inner<X, int> &that)
{
static_cast<basic_inner<X, int>&>(*this) = that;
return *this;
}
};
};
客户端代码是:
outer<double>::inner<void> x1;
outer<int>::inner<void> x2;
x1 = x2; // <-- error: no operator found which takes right-hand operand of type 'outer<int>::inner<void>'(or there is no acceptable conversion)
答案 0 :(得分:1)
我猜测由于名称隐藏,basic_inner
类的赋值运算符在派生类inner
中不可见。您可以将using basic_inner<X, T>::operator=;
添加到outer
课程中并获得此类内容。
template <typename T>
struct outer {
template <typename X>
struct inner : public basic_inner<X, T> {
using basic_inner<X, T>::operator=;
inner& operator=(const basic_inner<X, T>& that) {
static_cast<basic_inner<X, T>&>(*this) = that;
return *this;
}
};
};
template <>
struct outer<int> {
template <typename X>
struct inner : public basic_inner<X, int> {
using basic_inner<X, int>::operator=;
inner& operator=(const basic_inner<X, int>& that) {
static_cast<basic_inner<X, int>&>(*this) = that;
return *this;
}
};
};