简体   繁体   English

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

[英]Partial specialization for one method in the class

I have a template matrix class.我有一个模板矩阵 class。 I try to implement the size (always square) as a template parameter.我尝试将大小(始终为正方形)实现为模板参数。

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
{
    // ....
}

With this code, I would like to be able to make a different method for different sizes of matrix.使用此代码,我希望能够为不同大小的矩阵制作不同的方法。 Because some method force me to take it account without going in to dark code...因为某些方法迫使我在不进入暗码的情况下考虑它......

// For instance
void doSomething (void);

Is there a way like the following to be used?有没有类似下面的方法可以使用? Because I saw a lot of example and I have always an error.因为我看到了很多例子,我总是出错。 I use C++17 and GCC.我使用 C++17 和 GCC。 The final idea is to have only a header file.最后的想法是只有一个 header 文件。

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

    // ...
}

You might use SFINAE:您可以使用 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 would allow requires for better syntax: 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.
    }

    // ...
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM