我有这个带有乘法的最小表达式模板库,即
template <typename T, typename U>
struct mul {
const T &v1;
const U &v2;
};
template <typename T, typename U>
mul<T, U> operator*(const T &one, const U &two) {
std::cout << " called: mul<T, U> operator*(const T &one, const T &two)\n";
return mul<T, U>{one, two};
}
和转置,即
template <typename T>
struct transpose {
const T &t;
};
template <typename T>
transpose<T> tran(const T &one) {
return transpose<T>{one};
}
我将介绍一些类型A
和B
,其中后者是前者的子类:
template <typename T>
struct A {
T elem;
};
template <typename T>
struct B : A<T> {
B(T val) : A<T>{val} {}
};
然后,我可以按如下方式调用我的表达式模板库(带有用于打印到的重载std::cout
):
template <typename T, typename U>
std::ostream &operator<<(std::ostream &os, const mul<T, U> &m) {
os << " unconstrained template \n";
}
int main(int argc, char const *argv[]) {
B<double> a{2};
B<double> b{3};
std::cout << tran(a) * b << "\n";
return 0;
}
这给了我输出:
called: mul<T, U> operator*(const T &one, const T &two)
unconstrained template
到现在为止还挺好。现在假设我想要一个专门的处理方法来处理“类型变量的转置A<T>
乘以A<T>
某种类型的类型变量T
”,就像我在main
. 为此,我将介绍
template <typename T>
T operator*(const transpose<A<T>> &one, const A<T> &two) {
std::cout << " called: T operator*(const A<T> &one, const A<T> &two)\n";
return one.t.elem * two.elem;
}
我运行与main
上面相同的函数,我仍然得到与上面相同的输出(unconstrained template
)。这是意料之中的,因为transpose<B<double>>
与 相比是完全不同的类型transpose<A<double>>
,所以重载决议选择了operator*
.
(当然,如果我将变量定义更改main
为A
而不是B
,ADL 会调用专用函数并且输出是called: T operator*(const A<T> &one, const A<T> &two)
and 6
)。
我最近了解了 SFINAE,因此我预计对更具体的乘法运算符的以下更改会导致重载结果以选择专用函数:
template <typename T, typename V>
std::enable_if_t<std::is_base_of<A<T>, V>::value, T> operator*(const transpose<V> &one,
const V &two) {
std::cout << " called: std::enable_if_t<std::is_base_of<A<T>, V>::value, T> operator*(const "
"transpose<V> &one, const V &two)\n";
return one.t.elem * two.elem;
}
即使使用 SFINAE'doperator*
我仍然得到unconstrained template
版本。怎么会?我应该进行哪些更改来调用更专业的模板函数?