我一直在尝试为定点类型实现一个复数类,其中乘法运算的结果类型将是输入类型的函数。我需要具有可以将复数乘以复数以及复数乘以实数的功能。
这本质上是代码的简化版本。其中 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;
}
代码无法编译,因为编译器试图用and实例化a_rt模板。我不知道幕后发生了什么,因为我想编译器应该选择更专业的,所以只会作为参数实例化。doubleA<double>operator*(A<double>&)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> >' 
更新
编译器似乎对以下更改感到满意。我在这里缺少一些微妙之处。感谢能够引导我了解编译器在这两种情况下所做的事情的人。
    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;
    }