nij*_*sen 1 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;
};
};
Run Code Online (Sandbox Code Playgroud)
这编译和工作: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;
};
Run Code Online (Sandbox Code Playgroud)
但是我得到了一个我不明白的编译器错误:
Error: "typename Fraction<Numerator, Denominator>::add" uses "template<int Numerator, int Denominator> template <class Other> struct Fraction::add" which is not a type
Run Code Online (Sandbox Code Playgroud)
有人可以向我解释编译器说的是什么,为什么我不被允许做我想做的事情?我g++ 4.4.6顺便使用了.
使用template关键字.
template <class Other>
struct sub
{
typedef typename Fraction<Numerator, Denominator>::template add<
Fraction<-Other::numerator, -Other::denominator>
>::type type;
};
Run Code Online (Sandbox Code Playgroud)
http://liveworkspace.org/code/26f6314be690d14d1fc2df4755ad99f6
阅读本文以及为什么必须放置"模板"和"typename"关键字?为了更好的解释.