类中一种方法的部分专业化

问题描述 投票:0回答:1

我有一个模板矩阵类。我尝试将大小(始终为正方形)实现为模板参数。

template< 
    // Type of data
    typename type_t,
    // dimension of the matrix 4 -> 4x4 
    std::size_t dim_t, 
    // I don't want a matrix of non numeric value
    typename = typename std::enable_if_t< std::is_arithmetic_v< type_t >, type_t > 
>
class Matrix final
{
    // ....
}

通过此代码,我希望能够为不同大小的矩阵做出不同的方法。因为某种方法迫使我在不使用暗码的情况下考虑了这一点...

// For instance
void doSomething (void);

是否有使用以下方法的方式?因为我看到了很多例子,所以总是出错。我使用C ++ 17和GCC。最终的想法是只有一个头文件。

template< 
    typename type_t,
    std::size_t dim_t, 
    typename = typename std::enable_if_t< std::is_arithmetic_v< type_t >, type_t > 
>
class Matrix final
{
    // ...

    // Specialization for matrix 4x4
    template < typename type_t >
    void doSomething< type_t, 4 > (void)
    {
         // Specific code for matrix 4x4.
    }

    // ...
}
c++ templates partials specialization
1个回答
2
投票

您可以使用SFINAE:

template< 
    typename type_t,
    std::size_t dim_t, 
    typename = typename std::enable_if_t< std::is_arithmetic_v< type_t >, type_t > 
>
class Matrix final
{
    // ...

    // Specialization for matrix 4x4
    template <std::size_t N = dim_t, std::enable_if_t<N == 4, int> = 0>
    void doSomething()
    {
         // Specific code for matrix 4x4.
    }

    // ...
};

C ++ 20将允许使用requires获得更好的语法:

template< 
    typename type_t,
    std::size_t dim_t, 
    typename = typename std::enable_if_t< std::is_arithmetic_v< type_t >, type_t > 
>
class Matrix final
{
    // ...

    // Specialization for matrix 4x4
    void doSomething() requires(dim_t == 4)
    {
         // Specific code for matrix 4x4.
    }

    // ...
};
© www.soinside.com 2019 - 2024. All rights reserved.