嵌套模板类型 [英] nested template types

查看:174
本文介绍了嵌套模板类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要一个模板类型为模板类型:

I want to require a template type to be a templates type:

template < template < int beta, typename gamma> class alpha >
gamma foo()
{
    // do stuff with beta, gamma
    gamma c[beta]; 
    alpha a();
    alpha b();
}



我想要的gamma和beta由我给的值决定,因此:

I want to have gamma and beta decided by the values I give, so:

foo< hello<2,double> >()

将创建一个 hello< 2,double& code> object而不是 alpha c 将是一个数组 double

will create a hello<2,double> object instead of alpha, and c will be an array of double with 2 elements.

因此,我想从传递给foo的模板类中提取模板参数。

So, I want to extract the template parameters from the templated class passed to foo.

我如何做到这一点?

推荐答案

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

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.

这篇关于嵌套模板类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆