我在尝试 Visual Studio 10(Beta 2)时正在编写一些简单的点代码,并且我已经在我希望 SFINAE 启动的地方找到了这个代码,但它似乎没有:
template<typename T>
struct point {
T x, y;
point(T x, T y) : x(x), y(y) {}
};
template<typename T, typename U>
struct op_div {
typedef decltype(T() / U()) type;
};
template<typename T, typename U>
point<typename op_div<T, U>::type>
operator/(point<T> const& l, point<U> const& r) {
return point<typename op_div<T, U>::type>(l.x / r.x, l.y / r.y);
}
template<typename T, typename U>
point<typename op_div<T, U>::type>
operator/(point<T> const& l, U const& r) {
return point<typename op_div<T, U>::type>(l.x / r, l.y / r);
}
int main() {
point<int>(0, 1) / point<float>(2, 3);
}
这给error C2512: 'point<T>::point' : no appropriate default constructor available
鉴于它是一个测试版,我用在线 Comeau 编译器做了一个快速的健全性检查,它同意一个相同的错误,所以看起来这种行为是正确的,但我不明白为什么。
在这种情况下,一些解决方法是简单地内联decltype(T() / U())
, 给点类一个默认构造函数,或者在完整的结果表达式上使用 decltype ,但是我在尝试简化使用 op_div 版本时遇到的错误时遇到了这个错误不需要默认构造函数*,所以我宁愿修正我对 C++ 的理解,而不是只做有效的事情。
谢谢!
*: 原本的:
template<typename T, typename U>
struct op_div {
static T t(); static U u();
typedef decltype(t() / u()) type;
};
这给出了error C2784: 'point<op_div<T,U>::type> operator /(const point<T> &,const U &)' : could not deduce template argument for 'const point<T> &' from 'int'
,也给出了point<T> / point<U>
过载。