2017-12-16 7 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); 
} 

을 그리고 이것은 내가 이것을 사용하는 경우

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)); 
} 

하지만 난이 다항식 이진 첫 번째의 유형에 따라 얻을 것이다 neccesary 기능을 만들 수있는 내 시도 표현, 그리고 내가 필요로하는 것이 아닙니다.

마무리 질문 : 피연산자 유형을 기반으로 결과를 계산하지만 계정을 고려하지 않고 이항 연산자를 만들 수 있습니까? (간단 numberical 종류와 함께 작동하기 때문에 그것이 가능하지만, 내가 어떻게이 일을하는 아무 생각이 없음)

을 내가 std::vector<ScalarType> Here에서 다항식의 계수를 저장하고있어 내가 decltype()을 가정 전체 클래스 코드를

+2

을 테스트하지 전체 게시물을 읽어 보지 않았,하지만 당신은 ['표준 : common_type'] (HTTP 찾을 수 있습니다 : //en.cppreference를 .com/w/cpp/types/common_type) 유용합니다. – StoryTeller

답변

1

입니다 너를 도울 수있어.

뭔가

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

같은 PS :주의 :