本文介绍一种简单的
C++ Concept实现:给模板参数加限制。
1.背景
1.背景
#include <iostream>
using namespace std;
typedef long long int64;
struct BigInteger {
BigInteger(int64 v): value(v) {}
int64 value;
};
template<typename T>
BigInteger operator * (T v, const BigInteger& x) {
return BigInteger((int64)v * x.value);
}
struct Matrix {
};
int main() {
Matrix a;
BigInteger b(1);
a * b;
return 0;
}这里使用BigInteger作为例子(并未真正实现),其中提供了operator *,期望支持和所有基础的int类型相乘(当然,有其它方法实现,为了和本文配合而使用了代码中的实现)。但是,有可能对于非int类型也匹配了该函数模板,进而导致错误:
concept.c: In instantiation of 'BigInteger operator*(T, const BigInteger&) [with T = Matrix]':
concept.c:21:7: required from here
concept.c:12:21: error: invalid cast from type 'Matrix' to type 'int64 {aka long long int}'
return B

本文介绍了如何使用C++的模板概念给模板参数添加限制,以避免错误的模板匹配。通过示例展示了如何利用SFINAE原则和类型 traits 来确保模板仅接受特定类型的参数,例如基础的整型。在实现过程中,文章讨论了不同的实现方式及其优缺点,并分析了错误处理的效率和用户体验。
最低0.47元/天 解锁文章
3064

被折叠的 条评论
为什么被折叠?



