1
我想寫在編譯時做基本操作的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
。