std :: enable_if使用非类型模板参数

Los*_*ght 5 c++ templates c++11

你将如何在一个std::enable_if?中使用非类型模板参数比较?我无法弄清楚如何再次这样做.(我曾经有过这个工作,但是我丢失了代码,所以我无法回头看看,而且我找不到帖子,我找到了答案.)

提前感谢您对此主题的任何帮助.

template<int Width, int Height, typename T>
class Matrix{
    static
    typename std::enable_if<Width == Height, Matrix<Width, Height, T>>::type
    Identity(){
        Matrix ret;
        for (int y = 0; y < Width; y++){
            elements[y][y] = T(1);
        }
        return ret;
    }
}
Run Code Online (Sandbox Code Playgroud)

编辑:修复了注释中指出的缺失括号.

alf*_*lfC 5

这完全取决于您想在无效代码上引发什么样的错误/失败。这是一种可能性(撇开显而易见的static_assert(Width==Height, "not square matrix");

(C++98 风格)

#include<type_traits>
template<int Width, int Height, typename T>
class Matrix{
public:
    template<int WDummy = Width, int HDummy = Height>
    static typename std::enable_if<WDummy == HDummy, Matrix>::type
    Identity(){
        Matrix ret;
        for (int y = 0; y < Width; y++){
        // elements[y][y] = T(1);
        }
        return ret;
    }
};

int main(){
    Matrix<5,5,double> m55;
    Matrix<4,5,double> m45; // ok
    Matrix<5,5, double> id55 = Matrix<5,5, double>::Identity(); // ok
//  Matrix<4,5, double> id45 = Matrix<4,5, double>::Identity(); // compilation error! 
//     and nice error: "no matching function for call to ‘Matrix<4, 5, double>::Identity()"
}
Run Code Online (Sandbox Code Playgroud)

编辑:在C ++ 11的代码可以更紧凑和清晰的,(它的工作原理中clang 3.2,但不是在gcc 4.7.1,所以我不知道它是多么标准):

(C++11 风格)

template<int Width, int Height, typename T>
class Matrix{
public:
    template<typename = typename std::enable_if<Width == Height>::type>
    static Matrix
    Identity(){
        Matrix ret;
        for(int y = 0; y < Width; y++){
            // ret.elements[y][y] = T(1);
        }
        return ret;
    }
};
Run Code Online (Sandbox Code Playgroud)

2020 年编辑:(C++14)

template<int Width, int Height, typename T>
class Matrix{
public:
    template<typename = std::enable_if_t<Width == Height>>
    static Matrix
    Identity()
    {
        Matrix ret;
        for(int y = 0; y < Width; y++){
        //  ret.elements[y][y] = T(1);
        }
        return ret;
    }
};
Run Code Online (Sandbox Code Playgroud)

(C++20) https://godbolt.org/z/cs1MWj

template<int Width, int Height, typename T>
class Matrix{
public:
    static Matrix
    Identity()
        requires(Width == Height)
    {
        Matrix ret;
        for(int y = 0; y < Width; y++){
        //  ret.elements[y][y] = T(1);
        }
        return ret;
    }
};
Run Code Online (Sandbox Code Playgroud)