2015-04-24 34 views
0

我有一个通常由<double>实例化的模板类。在模板运算符中将int隐式转换为double * <>

我的头有一样的东西:

template <typename T> class F; 
// Non-member functions 
template <typename T> const F<T> operator*(F<T> lhs, const F<T>& rhs); 
template <typename T> const F<T> operator*(const F<T>& lhs, const T& rhs); 

template <typename T> 
class F 
{ 
    // blah blah 
    F<T>& operator*=(const F<T>& rhs); 
    F<T>& operator*=(const T& rhs_scalar); 
    // blah 
    friend const F<T> operator*(const F<T>& lhs, const T& rhs) { return F(lhs) *= rhs; } 
    friend const F<T> operator*(const T& lhs, const F<T>& rhs) { return F(rhs) *= lhs; } 
}; 

在我.cpp文件,我有这样的:

#include "F.H" 

// lots of template<typename T> returntype F<T>::function(args){ body } 
template <typename T> 
F<T>& F<T>::operator*=(const F<T>& rhs) 
{ 
    // check sizes, etc 
    // do multiplication 
    return *this; 
} 
template <typename T> 
F<T>& F<T>::operator*=(const T& rhs_scalar) 
{ 
    for(auto &lhs : field_) // field_ is a vector holding values 
    { 
     lhs *= rhs_scalar; 
    } 
    return *this; 
} 

// Non-member parts 
template <typename T> operator*(F<T> lhs, const F<T>& rhs) 
{ lhs *= rhs; return lhs; } 
template <typename T> operator*(const F<T>& lhs, const T& rhs) 
{ return F<T>(lhs) *= rhs; } 

template class F<double>; 
template const F<double> operator*<double>(F<double>, const F<double>&); 

这编译和运行正常,并允许的东西,如:

F<double> test(..); 
test *= 2.5; test *= 10; test /= 2.5; test /= 10; // and so on 

我的问题是:我可以减少声明的数量和定义我的运营商,同时保留隐式地将int升级到double等的能力?我可以重新排列代码,以便friend .. operator*(..)正文在头文件之外定义吗? (我怀疑这将涉及更具体的实例在标题和cpp文件之一或两者)

(附注:如何?斯科特迈耶的'有效C++'中的项目46描述隐式参数转换,但似乎是这样描述允许临时对象,允许建设(在这种情况下)Rational(int) * Rational_object_already_created;

回答

0

我可以减少声明和我的运营商定义的数量,同时保留了隐式推进的int的能力为double,等?

你可以通过提供一个转换构造函数来实现。

template <typename T2> 
    F(F<T2> const& f2) {...} 
+0

你的意思是我应该实现'double(int)'?因为我不想从'F '创建类'F '的对象 - 我只需要来自'int'的'double',否则(我想),'template 的特定函数运算符*(const F &,int)'和'template 运算符*(const F &,double)' - 但是这给了我更多的运算符来实现,做同样的事情(我想你会委派' F &,int)'到'(const F &,T)''使用'T {integer type argument}',但它仍然需要一大堆专业化... – chrisb2244

+0

我不清楚你是什么寻找更多。 –

相关问题