本文介绍一种简单的
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: requir