如何针对过程相似的不同数据类型专门化模板函数?

Hao*_*n Q 2 c++ templates

例如,我想使用AVX2实现一个矩阵乘法模板函数。(假设“Matrix”是一个实现良好的模板类)

Matrix<T> matmul(const Matrix<T>& mat1, const Matrix<T>& mat2) {
    if (typeid(T).name() == typeid(float).name()) {
        //using __m256 to store float
        //using __m256_load_ps __m256_mul_ps __m256_add_ps
    } else if (typeid(T).name() == typeid(double).name()) {
        //using __m256d to store double
        //using __m256d_load_pd __m256d_mul_pd __m256d_add_pd
    } else {
        //...
    }
}
Run Code Online (Sandbox Code Playgroud)

由于数据类型没有“变量”,程序无法确定是否应该使用 __m256 或 __m256d 或其他任何东西,从而使代码变得非常长和尴尬。还有其他方法可以避免这种情况吗?

Rem*_*eau 6

在 C++17 及更高版本中,您可以使用if constexpr

#include <type_traits>

Matrix<T> matmul(const Matrix<T>& mat1, const Matrix<T>& mat2) {
    if constexpr (std::is_same_v<T, float>) {
        //using __m256 to store float
        //using __m256_load_ps __m256_mul_ps __m256_add_ps
    } else if constexpr (std::is_same_v<T, double>) {
        //using __m256d to store double
        //using __m256d_load_pd __m256d_mul_pd __m256d_add_pd
    } else {
        //...
    }
}
Run Code Online (Sandbox Code Playgroud)

否则,只需使用重载:

Matrix<float> matmul(const Matrix<float>& mat1, const Matrix<float>& mat2) {
    //using __m256 to store float
    //using __m256_load_ps __m256_mul_ps __m256_add_ps
}

Matrix<double> matmul(const Matrix<double>& mat1, const Matrix<double>& mat2) {
    //using __m256d to store double
    //using __m256d_load_pd __m256d_mul_pd __m256d_add_pd
}

...
Run Code Online (Sandbox Code Playgroud)