繁体   English   中英

在模板结构外部重载运算符

[英]Overloading operator outside template struct

我有以下代码:

#include <iostream>
#include <stdio.h>
using namespace std;

template <class F>
struct CMPLX {

    F Re, Im;

    struct _printnice {
        F Re, Im;
        string sep;
        _printnice(const F& Re, const F& Im, const string& sep) : Re(Re), Im(Im), sep(sep) {}
    };

    CMPLX <F> (F Re, F Im) : Re(Re), Im(Im) {}

    _printnice PrintNice(const string& sep="\t"){
        return _printnice(Re, Im, sep);
    }

};

template<class F>
ostream& operator << (ostream& os, const CMPLX<F> c){
    cout << c.Re << " + " << c.Im << "i";
}

template<class F>
ostream& operator << (ostream& os, const CMPLX<F> :: _printnice p){
    cout << p.Re << p.sep << p.Im;
}

int main(){
    CMPLX<float> c(2.0,1.0);
    cout << c << endl;
    cout << c.PrintNice() << endl;

}

我介绍了一个子结构_printnice ,以便重载运算符<<并具有不同格式的CMPLX类输出。 但是,这会在'p'之前抛出一个错误预期的unqualified-id ,我不知道如何解决这个问题(我对模板的了解非常有限)。

我尝试将<<的第二个定义更改为以下哪个有效,但我必须指定类型,这是皱眉的:

ostream& operator << (ostream& os, const CMPLX <float> :: _printnice p){
    cout << p.Re << p.sep << p.Im;
}

您的方法有两个问题。 首先, _printnice是一个依赖名称,因此您需要添加一个额外的typename 如果这个问题得到解决,你最终会得到:

template<class F>
ostream& operator << (ostream& os, typename CMPLX<F>::_printnice const & p)

正如Dietmar在之前的回答中指出的那样,这段代码的问题在于F处于不可推导的环境中,这将失败。

一个简单的解决方案是在_printnice代码的范围内定义运算符,其中typename

template <class F>
struct CMPLX {
   //...
   struct _printnice {
      friend std::ostream& operator<<( std::ostream& o, _printnice const & p ) {
         // print here
         return o;
      }
   }
   //...
};

_printnice的定义中,已知类型是类型,因此不再需要typename 重载的operator<<将由Argument Dependent Lookup找到,并且因为它引用了该类型的特定实例化,所以没有要推导的模板参数。

在功能中:

template <typename F>
std::ostream& operator<<( std::ostream& os, CMPLX<F>::_printnice p);

F不是在可推断的背景下。 (见§14.8.2.5。)

NB。 这不是答案。 大卫已经回答了。 FWIW,只是解决了一些问题,因此它可以在gcc 4.72下编译和运行。

#include <iostream>
#include <stdio.h>
using namespace std;

template <class F>
struct CMPLX {

    F Re, Im;

    struct _printnice {

        F Re, Im;
        string sep;
        _printnice(const F& Re, const F& Im, const string& sep) : Re(Re), Im(Im), sep(sep) {}

        friend ostream& operator << (ostream& os, const _printnice& p){
            cout << p.Re << p.sep << p.Im;
            return os;
        }
    };

    CMPLX <F> (F Re, F Im) : Re(Re), Im(Im) {}

    _printnice PrintNice(const string& sep="\t"){
        return _printnice(Re, Im, sep);
    }

};

template<class F>
ostream& operator << (ostream& os, const CMPLX<F> c){
    cout << c.Re << " + " << c.Im << "i";
    return os;
}

int main() {
    CMPLX<float> c(2.0,1.0);
    cout << c << endl;
    cout << c.PrintNice() << endl;
}

//result
/*
2 + 1i
2       1
*/

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM