重载模板运算符 = 对于两个模板:template<...> A = template<...> B 反之亦然

Overload template operator= for two templates: template<...> A = template<...> B and vice versa

本文关键字:gt lt template 反之亦然 运算符 于两个 重载      更新时间:2023-10-16

>我正在实现两个模板类,其中一个类应具有另一个类的赋值运算符:

// prototype of template B
template<uint32_t nQ> class B;
// template A
template<uint32_t nQ> class A
{
    public:
        A<nQ>& operator = ( const B<nQ>& b );
};
// template B
template<uint32_t nQ> class B
{
    public:
        B<nQ>& operator = ( const A<nQ>& a ) { ... }
};
// Operator = for class A
template<uint32_t nQ>
A<nQ>& A<nQ>::operator = ( const B<nQ> b ) { ... }

目前为止,一切都好。完美工作。但是现在我想为不同的 nQ 值赋值运算符。虽然在模板 B 中这样做没有问题,但我无法让它适用于模板 A:

// prototype of template B
template<uint32_t nQ> class B;
// template A
template<uint32_t nQ> class A
{
    public:
        A<nQ>& operator = ( const B<nQ>& b );
};
// template B
template<uint32_t nQ> class B
{
    public:
        B<nQ>& operator = ( const A<nQ>& a ) { ... }
        /*
         * I want to have this operator in template A as well
         */
        template<uint32_t otherQ>
        B<nQ>& operator = ( const A<otherQ>& ) { ... }
};
// Operator = for class A
template<uint32_t nQ>
A<nQ>& A<nQ>::operator = ( const B<nQ>& b ) { ... }

不幸的是,运算符=不能实现为友元函数。我几乎尝试了所有方法,但我没有完成它。作为重要信息:我在自制的嵌入式硬件(STM32 + IAR嵌入式工作台(上使用C++14编译器。我真的很感激这里的帮助。

谢谢,蒂姆

以下内容应该有效:

// prototype of template B
template<uint32_t nQ> class B;
// template A
template<uint32_t nQ> class A
{
public:
    template <uint32_t OthernQ>
    A<nQ>& operator = ( const B<OthernQ>& b );
};
// template B
template<uint32_t nQ> class B
{
public:
    B<nQ>& operator = ( const A<nQ>& a ) { ... }
    template<uint32_t otherQ>
    B<nQ>& operator = ( const A<otherQ>& ) { ... }
};
// Operator = for class A
template <uint32_t nQ>
template <uint32_t OthernQ>
A<nQ>& A<nQ>::operator = ( const B<OthernQ>& b ) { ... }

类模板中方法模板的语法需要 2 template