C++ 非类型参数类的非类型参数成员函数的部分特化
我有一个带有C++ 非类型参数类的非类型参数成员函数的部分特化,c++,templates,template-specialization,specialization,C++,Templates,Template Specialization,Specialization,我有一个带有toString()方法的矩阵类: template <typename T, int rowCount, int columnCount> class Matrix { //... public: std::string toString() const { // ... } }; 在这种情况下: Matrix<double, 2, 2> a; std::string s = a.toString(); 矩阵a;
toString()
方法的矩阵类:
template <typename T, int rowCount, int columnCount>
class Matrix
{
//...
public:
std::string toString() const
{
// ...
}
};
在这种情况下:
Matrix<double, 2, 2> a;
std::string s = a.toString();
矩阵a;
std::string s=a.toString();
我试过这样的东西
template <int rows, int cols>
template <typename X, int rows_inside, int cols_inside>
std::string Matrix<Matrix<X, rows_inside, cols_inside>, rows, cols>::toString() const
{
//...
}
模板
模板
std::字符串矩阵::toString()常量
{
//...
}
但它不起作用
如何实现此效果?您可以使用
if constexpr
来实现此效果
模板
类矩阵;
模板
struct IsMatrix:std::false\u类型
{
};
模板
struct IsMatrix:std::true\u类型
{
};
模板
类矩阵
{
//...
公众:
std::string toString()常量
{
if constexpr(IsMatrix::value)
{
返回“矩阵”;
}
其他的
{
返回“非矩阵”;
}
}
};
这是否回答了您的问题?非常感谢你,这个很好用。你知道只有C++11功能才能实现这一点吗?@Julian Aßmann我看到了至少三种解决方案,第一种是使用部分专门化,有两个类版本,第二种是可以使用“标记分派”(通过实现将bool传递给底层函数),第三个最接近“if constexpr”的是使用std::enable_if。我为第三种方法写了一个例子:非常感谢!
template <int rows, int cols>
template <typename X, int rows_inside, int cols_inside>
std::string Matrix<Matrix<X, rows_inside, cols_inside>, rows, cols>::toString() const
{
//...
}