我有以下定义
template <typename T1, typename T2> class ArithmeticType {
public:
T1 x1;
T2 x2;
typedef typeof(x1+x2) Type;
};
template <typename D1, typename D2> inline
std::complex<typename ArithmeticType<D1,D2>::Type>
operator+(const std::complex<D1>& x1, const std::complex<D2>& x2) {
D1 x1r = real(x1);
D1 x1i = imag(x1);
D2 x2r = real(x2);
D2 x2i = imag(x2);
return std::complex<typename ArithmeticType<D1,D2>::Type>(x1r+x2r, x1i+x2i);
}
Run Code Online (Sandbox Code Playgroud)
然后,我按如下方式使用此类
std::complex<double> x;
std::cout << typeid(x).name() << std::endl;
ArithmeticType<std::complex<double>,std::complex<float>>::Type y;
std::cout << typeid(y).name() << std::endl;
Run Code Online (Sandbox Code Playgroud)
产生输出
St7complexIdE
St7complexIdE
Run Code Online (Sandbox Code Playgroud)
这对我来说很有意义: y属于std::complex<double>
现在,随着添加复杂和浮动类型的缩进,我添加了operator+模板的特殊化,因此代码变为
template …Run Code Online (Sandbox Code Playgroud)