我一直在尝试为定点类型实现一个复数类,其中乘法运算的结果类型将是输入类型的函数。我需要有一些函数,可以将复数乘以复数,也可以将复数乘以实数。
这本质上是代码的简化版本。其中 A 是我的复杂类型。
template<typename T1, typename T2> struct rt {};
template<> struct rt<double, double> {
typedef double type;
};
//forward declaration
template<typename T> struct A;
template<typename T1, typename T2>
struct a_rt {
typedef A<typename rt<T1,T2>::type> type;
};
template <typename T>
struct A {
template<typename T2>
typename a_rt<T,T2>::type operator*(const T2& val) const {
typename a_rt<T,T2>::type ret;
cout << "T2& called" << endl;
return ret;
}
template<typename T2>
typename a_rt<T,T2>::type operator*(const A<T2>& val) const {
typename a_rt<T,T2>::type ret;
cout << "A<T2>& called" << endl;
return ret;
}
};
TEST(TmplClassFnOverload, Test) {
A<double> a;
A<double> b;
double c;
a * b;
a * c;
}
代码无法编译,因为编译器正在尝试实例化a_rt
模板与double
and A<double>
。我不知道幕后发生了什么,因为我想编译器应该选择更专业的operator*(A<double>&)
so a_rt
只会被实例化<double, double>
作为参数。
您能向我解释一下为什么这行不通吗?
如果这是一个限制,我应该如何解决这个问题。
万分感谢!
unittest.cpp: In instantiation of 'a_rt<double, A<double> >':
unittest.cpp:198: instantiated from here
unittest.cpp:174: error: no type named 'type' in 'struct rt<double, A<double> >'
Update
编译器似乎对以下更改感到满意。我在这里缺少一些微妙之处。感谢能够引导我了解编译器在这两种情况下所做的事情的人。
template<typename T2>
A<typename rt<T,T2>::type> operator*(const T2& val) const {
A<typename rt<T,T2>::type> ret;
cout << "T2& called" << endl;
return ret;
}
template<typename T2>
A<typename rt<T,T2>::type> operator*(const A<T2>& val) const {
A<typename rt<T,T2>::type> ret;
cout << "A<T2>& called" << endl;
return ret;
}