作为对我最后一个问题的回答,建议尽可能std::common_type<X,Y>::type
在自动返回类型的声明中使用,而不是我原来的decltype()
. 但是,这样做我遇到了问题(使用 gcc 4.7.0)。考虑以下简单代码
template<typename> class A;
template<typename X> class A {
X a[3];
template <typename> friend class A;
public:
A(X a0, X a1, X a2) { a[0]=a0; a[1]=a1; a[2]=a2; }
X operator[](int i) const { return a[i]; }
X operator*(A const&y) const // multiplication 0: dot product with self
{ return a[0]*y[0] + a[1]*y[1] + a[2]*y[2]; }
template<typename Y>
auto operator*(A<Y> const&y) const -> // multiplication 1: dot product with A<Y>
#ifdef USE_DECLTYPE
decltype((*this)[0]*y[0])
#else
typename std::common_type<X,Y>::type
#endif
{ return a[0]*y[0] + a[1]*y[1] + a[2]*y[2]; }
template<typename Y>
auto operator*(Y s) const -> // multiplication 2: with scalar
#ifdef USE_DECLTYPE
A<decltype((*this)[0]*s)>
#else
A<typename std::common_type<X,Y>::type>
#endif
{ return A<decltype((*this)[0]*s)>(s*a[0],s*a[1],s*a[2]); }
};
int main()
{
A<double> x(1.2,2.0,-0.4), y(0.2,4.4,5.0);
A<double> z = x*4;
auto dot = x*y; // <--
std::cout<<" x*4="<<z[0]<<' '<<z[1]<<' '<<z[2]<<'\n'
<<" x*y="<<dot<<'\n';
}
什么时候,代码USE_DECLTYPE
可以#defined
在 gcc 4.7.0 下编译并运行良好。但除此之外,中指示的行main()
调用乘法 2,如果没有错的话,这似乎很奇怪。这可能是使用的后果/副作用std::common_type
还是 gcc 的错误?
我一直认为返回类型与选择众多拟合模板函数中的哪一个无关......