【问题标题】:Implicit conversion of int to double in template operator*<>在模板运算符 *<> 中将 int 隐式转换为 double
【发布时间】:2015-07-02 12:39:13
【问题描述】:

我有一个模板类,通常由&lt;double&gt; 实例化。

我的标题是这样的:

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 文件中的一个或两个中涉及更具体的实例化)

(旁注:如何?Scott Meyer 在“Effective C++”中的第 46 条描述了隐式参数转换,但它似乎描述了允许构造一个临时对象以允许(在这种情况下)Rational(int) * Rational_object_already_created;

【问题讨论】:

    标签: c++ class templates c++11


    【解决方案1】:

    我能否减少运算符的声明和定义数量,同时保留将 int 隐式提升为 double 等的能力?

    您可以通过提供转换构造函数来做到这一点。

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

    【讨论】:

    • 你的意思是我应该实现double(int)?因为我不想从F&lt;int&gt; 创建类F&lt;double&gt; 的对象-我只需要来自intdouble,或者(我想),template &lt;typename T&gt; operator*(const F&lt;T&gt;&amp;, int) 和@ 的特定函数987654330@ - 但这给了我更多的运营商来实现,做同样的事情(我想你会使用T{integer type argument}(const F&lt;T&gt;&amp;, int) 委托给(const F&lt;T&gt;&amp;, T),但它仍然需要一大堆专业知识......跨度>
    • 我不清楚你在寻找什么。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-08-18
    • 2020-05-03
    • 1970-01-01
    • 2012-02-11
    • 1970-01-01
    • 1970-01-01
    • 2015-02-05
    相关资源
    最近更新 更多