Home > Blockchain >  How to define a type dependent on template parameters
How to define a type dependent on template parameters

Time:10-04

I have a class that has methods that will return Eigen::Matrix types. However, when these will be 1x1 matrices, I want to just return double, as treating scalars as Eigen::Matrix<double, 1, 1> is a bit nasty. Essentially, I want something like this:

template <int rows, int cols>
class foo
{
    using my_type = ((rows == 1 && cols == 1) ? double : Eigen::Matrix<double, rows, cols>); 
};

However, this (unsurprisingly) doesn't work. How can I create the equivalent of the above?

CodePudding user response:

Use std::conditional_t<cond, TThen, TElse>:

template <int rows, int cols>
class foo
{
    using my_type = std::conditional_t<rows == 1 && cols == 1, double, Eigen::Matrix<double, rows, cols>>;
};

If you don't yet have std::conditional_t<>, you might try std::conditional<>::type (with typename prefix).

  • Related