且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

嵌套模板类型

更新时间:2022-04-26 21:57:37

模板参数(模板类型的模板参数)。然而,你提供的用法的例子尝试传递一个普通类作为参数(一旦所有模板参数被固定,模板类变成一个普通类,它不再是一个模板)。

The template declaration you provided take a so called template-template parameter (a template parameter of template type). Yet the example of usage you provided attempts to pass an "ordinary" class as an argument (once all template parameters are fixed, template class turns into an "ordinary" class, it is no longer a template).

这就意味着template-template参数不是你需要的。模板模板参数提供完全不同的目的。 (我不在这里详细说明)。

This immediately means that template-template parameter is not what you need. Template-template parameters serve a completely different purpose. (I won't go into details here).

您的问题的一个可能的解决方案是要求参数类通过嵌套类型和常量公开其模板参数。也就是说您的 hello 模板必须包含嵌套常量 beta_value 和嵌套类型名称 gamma_type

One possible solution for your problem is to require the argument classes to expose their template arguments through nested types and constants. I.e. your hello template must contain a nested constant beta_value and nested typename gamma_type

template <int BETA, typename GAMMA> class hello 
{
public:
  static const int beta_value = BETA;
  typedef GAMMA gamma_type;
  ...
};

在这种情况下,您的函数将使用普通类型模板参数

In this case your function will be declared with ordinary type template parameter

template <typename ALPHA> typename ALPHA::gamma_type foo()
{
   // do stuff with beta, gamma
   typename ALPHA::gamma_type c[ALPHA::beta_value]; 
   ALPHA a();
   ALPHA b();
}

如果某些用户忘记遵循约定,编译器将拒绝编译 foo 并强制用户更新其参数类的定义。

If some user forget to follow the convention, the compiler will refuse to compile foo and force that user to update the definition of their argument class.