分数元类减法方法不编译

时间:2012-10-25 12:23:39

标签: c++ metaprogramming

我正在尝试编写在编译时执行基本操作的struct Fraction。请注意,这并不是出于任何实际目的 - 我这只是一个练习。

我从这开始:

namespace internal
{
    // Euclid algorithm
    template <int A, int B>
    struct gcd
    {
        static int const value = gcd<B, A % B>::value;
    };

    // Specialization to terminate recursion
    template <int A>
    struct gcd<A, 0>
    {
        static int const value = A;
    };
}

template <int Numerator, int Denominator>
struct Fraction
{
    // Numerator and denominator simplified
    static int const numerator = Numerator / internal::gcd<Numerator, Denominator>::value;
    static int const denominator = Denominator / internal::gcd<Numerator, Denominator>::value;

    // Add another fraction
    template <class Other> struct add
    {
        typedef Fraction<
            Numerator * Other::denominator + Other::numerator * Denominator,
            Denominator * Other::denominator
        > type;
    };
};

这会编译并运作:Fraction<1,2>::add< Fraction<1,3> >::type将为Fraction<5,6>。现在我尝试添加减法:

template <class Other>
struct sub
{
    typedef typename Fraction<Numerator, Denominator>::add<
        Fraction<-Other::numerator, Other::denominator>
    >::type type;
};

但是我得到了一个我不理解的编译器错误:

Error: "typename Fraction<Numerator, Denominator>::add" uses "template<int Numerator, int Denominator> template <class Other> struct Fraction::add" which is not a type

有人可以向我解释一下编译器在说什么,为什么我不被允许做我想做的事情?我顺便使用g++ 4.4.6

1 个答案:

答案 0 :(得分:5)

使用模板关键字。

template <class Other>
struct sub
{
    typedef typename Fraction<Numerator, Denominator>::template add<
        Fraction<-Other::numerator, -Other::denominator>
    >::type type;
};

http://liveworkspace.org/code/26f6314be690d14d1fc2df4755ad99f6

请阅读此Where and why do I have to put the "template" and "typename" keywords?以获得更好的解释。