Search code examples
c++17eigen3

Convert template parameter into comma-separated list of template parameters


Apologies if the title is misleading or if this question has been answered before.

I'm working with Eigen's Tensor module, particularly the Eigen::TensorFixedSize class as I know the shape at compile time.

Essentially, because this is a Lorentz problem, a rank-2 tensor would go like,

Eigen::TensorFixedSize<double, Eigen::Sizes<4,4>> t;

a rank-3 tensor,

Eigen::TensorFixedSize<double, Eigen::Sizes<4,4,4>> t;

and so on.

I'd like to write a class that is able to initialise a tensor depending on the rank. In pseudo-code,

template<typename RANK>
 class Foo
 {
  public:
   ...
  private:
   Eigen::TensorFixedSize<double, Eigen::Sizes<4,4,4,...,RANK times>> _t;
 }

somehow converting the template parameter from

<2> --> <4,4>

<3> --> <4,4,4>

up to an arbitrary unsigned int in <N>.

Would this be possible to do?


Solution

  • Yup.

    template <class RankIdx>
    struct TensorForRank;
    
    template <std::size_t... RankIdx>
    struct TensorForRank<std::index_sequence<RankIdx...>> {
        using type = Eigen::TensorFixedSize<double, Eigen::Sizes<(void(RankIdx), 4)...>>;
    };
    
    template <std::size_t Rank>
    using TensorForRank_t = typename TensorForRank<std::make_index_sequence<Rank>>::type;
    

    Use as:

    template<std::size_t Rank>
    class Foo
    {
        // ...
    private:
        TensorForRank_t<Rank> _t;
    };
    

    See it live on Wandbox (with a placeholder test<...> template as Eigen is not available)