根据模板参数更改member-typedef吗? [英] Change member-typedef depending on template parameter?

查看:36
本文介绍了根据模板参数更改member-typedef吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在这里遇到这个问题,无法解决。我想要一个采用整数作为模板参数并相应地为另一个类设置模板参数的模板类:

I have this problem here that I can’t figure out how to solve. I want a template class that takes an integer as template parameter and sets the template parameters for another class accordingly:

template <int T>
class Solver
{

  public:

    #if T <= 24
      typedef MyMatrix<float> Matrix;
    #else if T <= 53
      typedef MyMatrix<double> Matrix;
    #else
      typedef MyMatrix<mpreal> Matrix;
    #endif

    Matrix create();

};

然后这样称呼它:

Solver<53>::Matrix m = Solver<53>::create();

我该怎么做?目前使用上面的代码,编译器抱怨它不知道 Matrix,所以我不确定是否可以对模板参数使用预处理器。

How can I do something like this? At the moment with the code above, the compiler complaints that it doesn't know "Matrix", so I'm not sure if you can use the preprocessor on template parameters.

推荐答案

简介


因为您希望 S< N> :: Matrix 根据传递的 N 产生不同的类型,您将需要使用某种元模板编程。该问题目前已被 preprocessor 标记,并且该代码段明确尝试使用它。

INTRODUCTION

Since you'd like S<N>::Matrix to yield a different type depending on the N passed, you will need to use some sort of meta template programming. The question is currently tagged with preprocessor, and the snippet explicitly tries to use it; but that is of little to no use in this case.

对代码进行预处理时, N 只是一个名字,它没有价值;

When the code is being preprocessed N is nothing more than a name, it hasn't got a value; yet.

描述中提到了 if if。 .. else else ;并且我们正在处理类型。.通过 < type_traits> 似乎是 std: :conditional 将是一个完美的匹配!

The description mentiones if, if ... else, and else; and we are dealing with types.. looking through <type_traits> it seems like std::conditional would be a perfect match!

std::conditional<condition, type-if-true, type-if-false>::type;

注意:取决于是否在中找到表达式条件产生 true ,或 false :: type 将是一个 typedef 表示 type-if-true type-if-false

Note: Depending on whether the expression found in condition yields true, or false, ::type will be a typedef for either type-if-true, or type-if-false.

让我们写一个示例实现:

Let's write a sample implementation:

#include <type_traits>

template <int N>
class Solver
{
  public:
    typedef typename std::conditional<
      /*    */ (N <= 24),
      /* y? */ MyMatrix<float>,
      /* n? */ typename std::conditional<(N <= 53), MyMatrix<double>, MyMatrix<mpreal>>::type
    >::type matrix_type;

  ...
};

int main () {
  Solver<53>::matrix_type a; // Matrix<double>
  Solver<10>::matrix_type b; // Matrix<float>
  Solver<99>::matrix_type c; // Matrix<mpreal>
}

这篇关于根据模板参数更改member-typedef吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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