在参数包中调用 base class operator= from derived
Call base class operator= from derived in parameter pack
我在 C++17 中实现了一个简单的程序,其中我尝试使用参数扩展从派生 class 调用基 class operator=
。但是程序不编译。
#include "pch.h"
#include <iostream>
class D
{
public:
D()
{
std::cout << "D ctror" << std::endl;
}
D & operator = (const D & other)
{
return *this;
}
};
class C
{
public:
C()
{
std::cout << "C ctror" << std::endl;
}
C & operator = (const C & other)
{
return *this;
}
};
class B
{
public:
B()
{
std::cout << "B ctror" << std::endl;
}
B & operator = (const B & other)
{
std::cout << "operator B" << std::endl;
return *this;
}
};
template<typename... Ts> class A: public Ts...
{
public:
A(): Ts()...
{
}
A & operator = (const A & other)
{
Ts::operator =(other);
return *this;
}
};
int main()
{
A<B,C,D> a1;
A<B,C,D> a2;
a1 = a2;
}
使用的工具集是 Visual Studio 2017 (v141)
生成的错误如下
error C3520: '=': parameter pack must be expanded in this context
note: while compiling class template member function 'A
&A::operator =(const A &)' note: see reference to
function template instantiation 'A &A::operator =(const
A &)' being compiled note: see reference to class template
instantiation 'A' being compiled
您需要扩展参数包。一个漂亮的折叠表达式怎么样:
(Ts::operator=(other), ...);
这将扩展 Ts...
并有效地创建对 operator=
的多个调用,包中的每种类型一个。
我在 C++17 中实现了一个简单的程序,其中我尝试使用参数扩展从派生 class 调用基 class operator=
。但是程序不编译。
#include "pch.h"
#include <iostream>
class D
{
public:
D()
{
std::cout << "D ctror" << std::endl;
}
D & operator = (const D & other)
{
return *this;
}
};
class C
{
public:
C()
{
std::cout << "C ctror" << std::endl;
}
C & operator = (const C & other)
{
return *this;
}
};
class B
{
public:
B()
{
std::cout << "B ctror" << std::endl;
}
B & operator = (const B & other)
{
std::cout << "operator B" << std::endl;
return *this;
}
};
template<typename... Ts> class A: public Ts...
{
public:
A(): Ts()...
{
}
A & operator = (const A & other)
{
Ts::operator =(other);
return *this;
}
};
int main()
{
A<B,C,D> a1;
A<B,C,D> a2;
a1 = a2;
}
使用的工具集是 Visual Studio 2017 (v141)
生成的错误如下
error C3520: '=': parameter pack must be expanded in this context note: while compiling class template member function 'A &A::operator =(const A &)' note: see reference to function template instantiation 'A &A::operator =(const A &)' being compiled note: see reference to class template instantiation 'A' being compiled
您需要扩展参数包。一个漂亮的折叠表达式怎么样:
(Ts::operator=(other), ...);
这将扩展 Ts...
并有效地创建对 operator=
的多个调用,包中的每种类型一个。