Change member-typedef depending on template parameter?

耗尽温柔 提交于 2019-12-04 06:42:08

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.

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


Solution

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;

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>
}

You can use std::conditional for this, although whether you should be doing this in the first place is another kettle of fish:

template<int T>
class Solver
{
  std::conditional_t<
    T <= 24,
    MyMatrix<float>,
    std::conditional_t<
      T <= 53,
      MyMatrix<double>,
      MyMatrix<mpreal>
    >
  > Matrix;
};

You'll need to use std::conditional and ::type instead of conditional_t if your compiler doesn't support it.

Peter

No, you can't use the preprocessor on template parameters.

The preprocessor is just doing very simple string processing on your input source. It has no glue about types and I think it is run as the very first step while first processing the file and collecting all the includes. Templates are something the compiler itself takes care of. At this point the preprocessor has finished already.

A similar question has been asked here: Use a template parameter in a preprocessor directive?

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!