从参数包中派生调用基类operator =

时间:2019-06-23 14:19:55

标签: c++ c++17 variadic-templates

我用C ++ 17实现了一个简单的程序,其中我尝试使用参数扩展从派生类中调用基类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)

生成的错误如下

  

错误C3520:'=':必须在这种情况下扩展参数包   注意:在编译类模板成员函数'A时   &A :: operator =(const A&)'注意:请参阅参考   函数模板实例化'A&A :: operator =(const   一个&)'正在被编译的注释:请参见对类模板的引用   实例化“ A”正在编译

1 个答案:

答案 0 :(得分:2)

您需要扩展参数包。折叠效果如何?

(Ts::operator=(other), ...);

这将展开Ts...,并有效地创建对operator=的多个调用,包中的每种类型一个。

相关问题