gpt4 book ai didi

c++ - 在模板结构外重载运算符

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:47:15 24 4
gpt4 key购买 nike

我有以下代码:

#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 有不同格式的输出类(class)。但是,这会引发错误expected unqualified-id before ‘p’ 我不知道如何解决这个问题(我对模板的了解非常有限)。

我尝试更改 << 的第二个定义以下是有效的,但我必须指定类型,这是不受欢迎的:

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 找到,并且因为它指的是类型的这个特定实例化,所以没有模板参数可以推导。

关于c++ - 在模板结构外重载运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12900298/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com