Search code examples
c++c++11templatestypedefusing

Reducing template parameter with using or typedef


I'm trying to increase my code readabiliy by introducing the "using" keyword.

namespace EigenRM
{
    template<typename T>
    using MatrixX<T> = Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor>;
}

This code is not working. I've seen examples using "using" to remove all template parameters but none for retaining one. Is this even possible?


Solution

  • Try removing the <T> after MatrixX

    template<typename T>
    using MatrixX<T> = Eigen::Matrix<T, ...
    // wrong ....^^^
    

    If you precede the using definition of a name foo with a template declaration, it's implicit that you're defining the template argument over foo, so simply

    namespace EigenRM
    {
        template<typename T>
        using MatrixX = Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor>;
    }
    

    -- EDIT --

    The OP says

    This is exactly what i am not trying to do. I am trying to write EigenRM::MatrixX<double> //instead of Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor> within an untemplated function

    This is exactly what you get if you remove the "<T>": EigenRM::MatrixX<double> become an alias for Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor>.

    I'm without an Eigen installation but the following example should explain what I mean

    #include <type_traits>
    
    template <typename, typename, typename>
    struct foo;
    
    template <typename T>
    using bar = foo<T, float, int>;
    
    int main ()
     {
       static_assert(std::is_same< bar<double>,
                                   foo<double, float, int> >{}, "!");
     }