模板函数重载和 SFINAE 实现
Template function overloading and SFINAE implementations
我花了一些时间学习如何在C++中使用模板。我从未使用过它们 之前,我并不总是确定在不同情况下可以实现什么或无法实现什么。
作为练习,我正在包装一些用于活动的 Blas 和 Lapack 函数, 我目前正在研究?GELS
的包装(评估一组线性方程的解)。
A x + b = 0
?GELS
函数(仅适用于实值)存在两个名称:SGELS
,用于单精度向量和DGELS
双精度。
我对接口的想法是这样solve
的函数:
const std::size_t rows = /* number of rows for A */;
const std::size_t cols = /* number of cols for A */;
std::array< double, rows * cols > A = { /* values */ };
std::array< double, ??? > b = { /* values */ }; // ??? it can be either
// rows or cols. It depends on user
// problem, in general
// max( dim(x), dim(b) ) =
// max( cols, rows )
solve< double, rows, cols >(A, b);
// the solution x is stored in b, thus b
// must be "large" enough to accommodate x
根据用户要求,问题可能过度确定或未确定,这意味着:
- 如果
dim(b) > dim(x)
超定(解为伪逆) - 如果不确定
dim(b) < dim(x)
(解决方案是LSQ最小化) - 或正常情况下
dim(b) = dim(x)
(解是A
的倒数)
(不考虑单一情况)。
由于?GELS
将结果存储在输入向量b
中,因此std::array
应该 有足够的空间来容纳解决方案,如代码注释 (max(rows, cols)
中所述。
我想(编译时)确定采用哪种解决方案(这是参数更改) 在?GELS
电话中)。我有两个功能(为了这个问题,我正在简化), 处理精度并且已经知道哪个是b
的维度和rows
/cols
的数量:
namespace wrap {
template <std::size_t rows, std::size_t cols, std::size_t dimb>
void solve(std::array<float, rows * cols> & A, std::array<float, dimb> & b) {
SGELS(/* Called in the right way */);
}
template <std::size_t rows, std::size_t cols, std::size_t dimb>
void solve(std::array<double, rows * cols> & A, std::array<double, dimb> & b) {
DGELS(/* Called in the right way */);
}
}; /* namespace wrap */
是内部包装器的一部分。用户功能,确定所需的大小 在通过模板的b
矢量中:
#include <type_traits>
/** This struct makes the max between rows and cols */
template < std::size_t rows, std::size_t cols >
struct biggest_dim {
static std::size_t const value = std::conditional< rows >= cols, std::integral_constant< std::size_t, rows >,
std::integral_constant< std::size_t, cols > >::type::value;
};
/** A type for the b array is selected using "biggest_dim" */
template < typename REAL_T, std::size_t rows, std::size_t cols >
using b_array_t = std::array< REAL_T, biggest_dim< rows, cols >::value >;
/** Here we have the function that allows only the call with b of
* the correct size to continue */
template < typename REAL_T, std::size_t rows, std::size_t cols >
void solve(std::array< REAL_T, cols * rows > & A, b_array_t< REAL_T, cols, rows > & b) {
static_assert(std::is_floating_point< REAL_T >::value, "Only float/double accepted");
wrap::solve< rows, cols, biggest_dim< rows, cols >::value >(A, b);
}
通过这种方式,它实际上有效。但我想更进一步,我真的不知道该怎么做。 如果用户尝试使用b
太小的大小调用solve
,编译器会引发极其难以读取的错误。
我正在尝试插入 帮助用户理解其错误的static_assert
。但是我想到的任何方向 需要使用两个具有相同签名的函数(就像模板重载? 我找不到 SFINAE 策略(而且它们实际上根本不编译)。
您是否认为可以在编译时不更改用户界面的情况下为错误b
维度的情况提出静态断言? 我希望这个问题足够清楚。
@Caninonos:对我来说,用户界面是用户调用求解器的方式,即:
solve< type, number of rows, number of cols > (matrix A, vector b)
这是我为了提高技能而对锻炼施加的限制。这意味着,我不知道是否真的有可能实现解决方案。b
的类型必须与函数调用匹配,如果我添加另一个模板参数并更改用户界面,这很容易,这违反了我的约束。
最小完整和工作示例
这是一个最小的完整和工作示例。根据要求,我删除了对线性代数概念的任何引用。这是一个数量问题。这些案例是:
N1 = 2, N2 =2
.从N3 = max(N1, N2) = 2
一切正常N1 = 2, N2 =1
.从N3 = max(N1, N2) = N1 = 2
开始一切正常N1 = 1, N2 =2
.从N3 = max(N1, N2) = N2 = 2
开始一切正常N1 = 1, N2 =2
.由于N3 = N1 = 1 < N2
它正确地引发了编译错误。我想用一个静态断言来拦截编译错误,该断言解释了N3
维度错误的事实。至于现在,错误很难阅读和理解。
您可以在此处在线查看和测试
首先,一些改进可以简化设计并提高可读性:
没有必要biggest_dim
.std::max
自 C++14 年以来一直是 constexpr。您应该改用它。
不需要b_array_t
.你可以写std::array< REAL_T, std::max(N1, N2)>
现在谈谈你的问题。C++17 中的一个好方法是:
template < typename REAL_T, std::size_t N1, std::size_t N2, std::size_t N3>
void solve(std::array< REAL_T, N1 * N2 > & A, std::array< REAL_T, N3> & b) {
if constexpr (N3 == std::max(N1, N2))
wrap::internal< N1, N2, N3 >(A, b);
else
static_assert(N3 == std::max(N1, N2), "invalid 3rd dimension");
// don't write static_assert(false)
// this would make the program ill-formed (*)
}
或者,正如@max66所指出的
template < typename REAL_T, std::size_t N1, std::size_t N2, std::size_t N3>
void solve(std::array< REAL_T, N1 * N2 > & A, std::array< REAL_T, N3> & b) {
static_assert(N3 == std::max(N1, N2), "invalid 3rd dimension");
if constexpr (N3 == std::max(N1, N2))
wrap::internal< N1, N2, N3 >(A, b);
}
哒!!简单,优雅,漂亮的错误消息。
constexpr if 版本和只是一个static_assert
之间的区别,即:
void solve(...)
{
static_assert(...);
wrap::internal(...);
}
就是编译器即使失败static_assert
也会尝试实例化wrap::internal
static_assert
,从而污染错误输出。使用 constexpr 如果对wrap::internal
的调用不是正文的一部分,则条件失败,因此错误输出是干净的。
(*) 我之所以没有写static_asert(false, "error msg)
,是因为这将使程序格式不正确,不需要诊断。参见 constexpr if 和 static_assert
如果需要,您还可以通过将模板参数移动到不可扣除参数之后来使float
/double
可扣除:
template < std::size_t N1, std::size_t N2, std::size_t N3, typename REAL_T>
void solve(std::array< REAL_T, N1 * N2 > & A, std::array< REAL_T, N3> & b) {
因此,调用变为:
solve< n1_3, n2_3>(A_3, b_3);
你为什么不尝试将标签调度与一些static_assert
结合起来呢?我希望以下是实现您想要解决的问题的一种方法。我的意思是,所有三个正确的案例都正确地管道到正确的blas
调用,处理不同类型和维度不匹配,并且还处理了关于float
和double
s 的违规行为,所有这些都以用户友好的方式处理,这要归功于static_assert
.
我不确定您的C++
版本要求,但以下是C++11
友好的。
#include <algorithm>
#include <iostream>
#include <type_traits>
template <class value_t, int nrows, int ncols> struct Matrix {};
template <class value_t, int rows> struct Vector {};
template <class value_t> struct blas;
template <> struct blas<float> {
static void overdet(...) { std::cout << __PRETTY_FUNCTION__ << std::endl; }
static void underdet(...) { std::cout << __PRETTY_FUNCTION__ << std::endl; }
static void normal(...) { std::cout << __PRETTY_FUNCTION__ << std::endl; }
};
template <> struct blas<double> {
static void overdet(...) { std::cout << __PRETTY_FUNCTION__ << std::endl; }
static void underdet(...) { std::cout << __PRETTY_FUNCTION__ << std::endl; }
static void normal(...) { std::cout << __PRETTY_FUNCTION__ << std::endl; }
};
class overdet {};
class underdet {};
class normal {};
template <class T1, class T2, int nrows, int ncols, int dim>
void solve(const Matrix<T1, nrows, ncols> &lhs, Vector<T2, dim> &rhs) {
static_assert(std::is_same<T1, T2>::value,
"lhs and rhs must have the same value types");
static_assert(dim >= nrows && dim >= ncols,
"rhs does not have enough space");
static_assert(std::is_same<T1, float>::value ||
std::is_same<T1, double>::value,
"Only float or double are accepted");
solve_impl(lhs, rhs,
typename std::conditional<(nrows < ncols), underdet,
typename std::conditional<(nrows > ncols), overdet,
normal>::type>::type{});
}
template <class value_t, int nrows, int ncols, int dim>
void solve_impl(const Matrix<value_t, nrows, ncols> &lhs,
Vector<value_t, dim> &rhs, underdet) {
/* get the pointers and dimension information from lhs and rhs */
blas<value_t>::underdet(
/* trans, m, n, nrhs, A, lda, B, ldb, work, lwork, info */);
}
template <class value_t, int nrows, int ncols, int dim>
void solve_impl(const Matrix<value_t, nrows, ncols> &lhs,
Vector<value_t, dim> &rhs, overdet) {
/* get the pointers and dimension information from lhs and rhs */
blas<value_t>::overdet(
/* trans, m, n, nrhs, A, lda, B, ldb, work, lwork, info */);
}
template <class value_t, int nrows, int ncols, int dim>
void solve_impl(const Matrix<value_t, nrows, ncols> &lhs,
Vector<value_t, dim> &rhs, normal) {
/* get the pointers and dimension information from lhs and rhs */
blas<value_t>::normal(
/* trans, m, n, nrhs, A, lda, B, ldb, work, lwork, info */);
}
int main() {
/* valid types */
Matrix<float, 2, 4> A1;
Matrix<float, 4, 4> A2;
Matrix<float, 5, 4> A3;
Vector<float, 4> b1;
Vector<float, 5> b2;
solve(A1, b1);
solve(A2, b1);
solve(A3, b2);
Matrix<int, 4, 4> A4;
Vector<int, 4> b3;
// solve(A4, b3); // static_assert for float & double
Matrix<float, 4, 4> A5;
Vector<int, 4> b4;
// solve(A5, b4); // static_assert for different types
// solve(A3, b1); // static_assert for dimension problem
return 0;
}
<</div>
div class="answers">你必须考虑为什么接口提供这种(复杂的)混乱的参数。作者想到了几件事。首先,您可以在一个函数中解决形式A x + b == 0
和A^T x + b == 0
的问题。其次,给定的A
和b
实际上可以指向大于 alg 所需矩阵中的内存。这可以通过LDA
和LDB
参数看到。
正是子寻址使事情变得复杂。如果你想要一个简单但可能足够有用的API,你可以选择忽略该部分:
using ::std::size_t;
using ::std::array;
template<typename T, size_t rows, size_t cols>
using matrix = array<T, rows * cols>;
enum class TransposeMode : bool {
None = false, Transposed = true
};
// See https://stackoverflow.com/questions/14637356/
template<typename T> struct always_false_t : std::false_type {};
template<typename T> constexpr bool always_false_v = always_false_t<T>::value;
template < typename T, size_t rowsA, size_t colsA, size_t rowsB, size_t colsB
, TransposeMode mode = TransposeMode::None >
void solve(matrix<T, rowsA, colsA>& A, matrix<T, rowsB, colsB>& B)
{
// Since the algorithm works in place, b needs to be able to store
// both input and output
static_assert(rowsB >= rowsA && rowsB >= colsA, "b is too small");
// LDA = rowsA, LDB = rowsB
if constexpr (::std::is_same_v<T, float>) {
// SGELS(mode == TransposeMode::None ? 'N' : 'T', ....);
} else if constexpr (::std::is_same_v<T, double>) {
// DGELS(mode == TransposeMode::None ? 'N' : 'T', ....);
} else {
static_assert(always_false_v<T>, "Unknown type");
}
}
现在,用LDA
和LDB
解决可能的子寻址。我建议你把这部分作为数据类型的一部分,而不是直接成为模板签名的一部分。您希望拥有自己的矩阵类型,该类型可以引用矩阵中的存储。也许是这样的:
// Since we store elements in a column-major order, we can always
// pretend that our matrix has less columns than it actually has
// less rows than allocated. We can not equally pretend less rows
// otherwise the addressing into the array is off.
// Thus, we'd only four total parameters:
// offset = columnSkipped * actualRows + rowSkipped), actualRows, rows, cols
// We store the offset implicitly by adjusting our begin pointer
template<typename T, size_t rows, size_t cols, size_t actualRows>
class matrix_view { // Name derived from string_view :)
static_assert(actualRows >= rows);
T* start;
matrix_view(T* start) : start(start) {}
template<typename U, size_t r, size_t c, size_t ac>
friend class matrix_view;
public:
template<typename U>
matrix_view(matrix<U, rows, cols>& ref)
: start(ref.data()) { }
template<size_t rowSkipped, size_t colSkipped, size_t newRows, size_t newCols>
auto submat() {
static_assert(colSkipped + newCols <= cols, "can only shrink");
static_assert(rowSkipped + newRows <= rows, "can only shrink");
auto newStart = start + colSkipped * actualRows + rowSkipped;
using newType = matrix_view<T, newRows, newCols, actualRows>
return newType{ newStart };
}
T* data() {
return start;
}
};
现在,您需要使接口适应这种新数据类型,这基本上只是引入了一些新参数。检查基本保持不变。
// Using this instead of just type-defing allows us to use deducation guides
// Replaces: using matrix = std::array from above
template<typename T, size_t rows, size_t cols>
class matrix {
public:
std::array<T, rows * cols> storage;
auto data() { return storage.data(); }
auto data() const { return storage.data(); }
};
extern void dgels(char TRANS
, integer M, integer N , integer NRHS
, double* A, integer LDA
, double* B, integer LDB); // Mock, missing a few parameters at the end
// Replaces the solve method from above
template < typename T, size_t rowsA, size_t colsA, size_t actualRowsA
, size_t rowsB, size_t colsB, size_t actualRowsB
, TransposeMode mode = TransposeMode::None >
void solve(matrix_view<T, rowsA, colsA, actualRowsA> A, matrix_view<T, rowsB, colsB, actualRowsB> B)
{
static_assert(rowsB >= rowsA && rowsB >= colsA, "b is too small");
char transMode = mode == TransposeMode::None ? 'N' : 'T';
// LDA = rowsA, LDB = rowsB
if constexpr (::std::is_same_v<T, float>) {
fgels(transMode, rowsA, colsA, colsB, A.data(), actualRowsA, B.data(), actualRowsB);
} else if constexpr (::std::is_same_v<T, double>) {
dgels(transMode, rowsA, colsA, colsB, A.data(), actualRowsA, B.data(), actualRowsB);
// DGELS(, ....);
} else {
static_assert(always_false_v<T>, "Unknown type");
}
}
用法示例:
int main() {
matrix<float, 5, 5> A;
matrix<float, 4, 1> b;
auto viewA = matrix_view{A}.submat<1, 1, 4, 4>();
auto viewb = matrix_view{b};
solve(viewA, viewb);
// solve(viewA, viewb.submat<1, 0, 2, 1>()); // Error: b is too small
// solve(matrix_view{A}, viewb.submat<0, 0, 5, 1>()); // Error: can only shrink (b is 4x1 and can not be viewed as 5x1)
}
- 如果没有malloc,链表实现将失败
- 如何在c++中实现处理器调度模拟器
- 如何在c++中使用引用实现类似python的行为
- 实现无开销push_back的最佳方法是什么
- 为什么使用SFINAE而不是函数重载
- 使用简单类型列表实现的指数编译时间.为什么
- 如何使用模板函数的函数签名进行SFINAE
- 数据成员SFINAE的C++17测试:gcc vs clang
- 使用在用于SFINAE的void_t中具有参数的方法
- 如何在BST的这个简单递归实现中消除警告
- 基于 SFINAE 的特征实现问题与函数模板重载
- 有没有一种方法可以使用SFINAE来检测一个类型是否实现了给定的抽象基类
- 关于如何使用此代码段实现 SFINAE 的问题
- 模板函数重载和 SFINAE 实现
- 使用 SFINAE 实现 get_as() 的 ConfigParser<type>
- 在 if-else 块中实现类似 SFINAE 的效果
- 使用 SFINAE 在 Clase 模板中选择不同的方法实现
- 如果未实现除法运算符,则SFINAE回退
- SFINAE使用模板、专门化和实现类型擦除
- 使用SFINAE选择要实现的接口