这完全取决于您希望在无效代码上引发什么样的错误/故障。以下是一种可能性(抛开明显的 static_assert(Width==Height, "not square matrix");
)
(C++98风格)
#include<type_traits>
template<int Width, int Height, typename T>
class Matrix
return ret;
}
};
int main()
编辑: 在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++){
}
return ret;
}
};
编辑 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++){
}
return ret;
}
};
(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++){
}
return ret;
}
};
static_assert
来实现。它可以提供清晰的错误信息。 - chrisstatic_assert
确实是正确的工具:std::enable_if
用于SFINAE,而对于类模板的非模板成员,不存在SFINAE。 - Luc Dantonstatic_assert
,最终可能会使用它。但是在此之前,我已经让它工作了,并且由于自动完成不会在第一时间列出非方阵矩阵的函数,因此具有优势。然而,目前主要是试图弄清楚我曾经如何仅使用std::enable_if
来完成这项任务。 - LostOfThoughtenable_if
行末少了一个>
。实际上(在修正后)您的代码可以工作,但它与static_assert
没有区别(当调用非方阵矩阵类型时,会给出编译错误)。 它只比static_assert
更晦涩难懂。 - alfC