泛型编程中带有关键字模板的规范

Specification with keyword template in the generic programming

本文关键字:关键字 泛型编程      更新时间:2023-10-16
#include <iostream>
namespace oo{
  class A{
  public:
    template<typename T>
    static T get_value(){return static_cast<T>(55);}
  };
  template <typename T=A>
  class B{
    public:
    static double f(){return T::get_value<double>();}
  };
}
int main(int argc, char *argv[])
{
  using std::cout;
  using std::endl;
  cout << oo::B<oo::A>::f() << endl;
  return 0;
}

考虑到这里的例子,它编译时出现错误"不允许类型名称",该错误引用"double"和"get_value(("中的参数。

有人通过重写函数 f(( 来纠正这个错误,如下所示:

static double f(){return T::template get_value<double>(); }

然而,我不太明白这里"模板"的使用。谁能向我解释一下,请?

提前感谢您的评论。

原因是编译器如何解释那行,当你使用模板时,语法有多个可能的解释,看看下面:

static double f()
{
    return T::get_value < double > ();
}

在您的函数中,您现在传递给 B 类的 T 参数如何具有名为 get_value 的函数或名为 get_value 的数据成员?如果情况是第二种,则在该成员和双精度之间,然后在双精度和 (( 之间使用运算符 lees-than。那么编译器的第一个假设是这些选项,如果你告诉他这是一个带有模板的函数(为了正确解释"<"(,你需要把关键字模板

这就是

运行时发生的事情。

namespace oo{
  class A{  
  public:
   // template<typename T>  // T replaced with <double> type.
    static double get_value(){return static_cast<double>(55);}
  };
  //template <typename T=A> // T replaced with <oo::A> type.
  class B{
    public:
    static double f(){return oo::A::get_value/*<double>*/();}
  };
}
int main(int argc, char *argv[])
{
  using std::cout;
  using std::endl;
  cout << oo::B::f() << endl;
  return 0;
}

这一行: 静态双精度 f(({return T::get_value((;}是正确的,通常编译时没有任何错误(取决于您使用的女巫编译器(,因为模板声明对下一个范围有效。

template <class T>
class foo
{
   //T will be valid in this scope.
};

实现模板类/函数不是这种情况,在想要防止使用多个重载的情况下,您通常希望这样做。