2017-12-16 21 views
-2

オーバーロードされた演算子 "+"を使用してテンプレートPolynomicalクラスを作成しようとしています。私は同じ変数型(int + int)に基づいているオブジェクトでこれを動作させることができましたが、今はさまざまな種類の変数(float + int)に基づいてオブジェクトを扱うようにこれを適応させています。 私は集計している多項式の型に基づいてどのような結果を得るかを選択したいと思います。このようなもの:バイナリ演算子のオーバーロード

float + int -> float; 
float + double -> double; 
int + int -> int; 
unsigned int + int -> int; 

などです。

今私は、次のコードしている:

template <class ScalarType> 
    class Polynomial { 

    public: 
     Polynomial<ScalarType> operator+ (const Polynomial<ScalarType>& other) const; 

} 

template <class ScalarType> 
Polynomial<ScalarType> Polynomial<ScalarType>::operator+ (const Polynomial<ScalarType>& other) const { 
    bool firstIsMore = this->size() > other.size(); 
    Polynomial<ScalarType> result(firstIsMore ? *this : other); 

    typename std::vector<ScalarType>::iterator resultIt = result.nc_begin(); 
    typename std::vector<ScalarType>::const_iterator summIterBegin = (firstIsMore ? other.begin() : this->begin()); 
    typename std::vector<ScalarType>::const_iterator summIterEnd = (firstIsMore ? other.end() : this->end()); 

    while (summIterBegin != summIterEnd) { 
    *resultIt += *summIterBegin; 
    resultIt++; 
    summIterBegin++; 
    } 

    return(result); 
} 

をし、これがneccesary機能

template <class OtherScalar> 
    Polynomial<ScalarType> operator+ (const Polynomial<OtherScalar>& other) const; 


template <class ScalarType> 
class Polynomial { 

public: 

    template <class OtherScalar> 
    Polynomial<ScalarType> operator+ (const Polynomial<OtherScalar>& other) const; 

} 

template <class ScalarType> 
template <class OtherScalar> 
Polynomial<ScalarType> Polynomial<ScalarType>::operator+ (const Polynomial<OtherScalar>& other) const { 

    std::vector<ScalarType> summResult = this->getCoefficients(); 
    std::vector<OtherScalar> toSumm = other.getCoefficients(); 

    std::transform(summResult.begin(), 
       summResult.end(), 
       toSumm.begin(), 
       summResult.begin(), 
       [](const ScalarType& first, const OtherScalar& second){return (first + second);}); 

    if (summResult.size() < toSumm.size()) { 
    summResult.insert(summResult.end(), toSumm.begin() + (toSumm.size() - summResult.size()), toSumm.end()); 
    } 

    return(Polynomial(summResult)); 
} 

を作成する私の試みですが、私はこれを使用する場合、私はバイナリの最初の1のタイプに基づいて多項式を取得します私が必要としているものではないことを示しています。

最終的な質問:オペランドの型に基づいて結果を返すバイナリ演算子を作成できますが、その順序は考慮されません。 (それは簡単なnumbericalタイプで動作しますので、それは可能ですが、私はこの作品を作るためにどのようには考えている)

私はstd::vector<ScalarType> Hereに多項式の係数を格納しています完全なクラスコード

+2

テストされていません。//en.cppreferenceを.com/w/cpp/types/common_type)が便利です。 – StoryTeller

答えて

1

である私はdecltype()を想定あなたを助けることができます。

何か

template <class OtherScalar> 
Polynomial<decltype(ScalarType()+OtherScalar())> operator+ 
    (const Polynomial<OtherScalar>& other) const; 

のようなPS:注意:全体の記事を読んでいないが、あなたは[ `のstd :: common_type`](HTTP見つけることができ

関連する問題