簡體   English   中英

錯誤:“operator+=”不匹配(操作數類型為“long double”和“std::__cxx11::basic_string”<char> &#39;)

[英]error: no match for 'operator+=' (operand types are 'long double' and 'std::__cxx11::basic_string<char>')

我需要從可以是任何數據類型的元組中讀取值,然后如果它們是數字就添加它們,或者如果它們可轉換為字符串則將它們連接起來。

tuple<int32_t, bool, string, float, const char*, char, int> t{10, true, "Modern", 2.3f, "C++", 'e', 13}; // Example Tuple

因此,我認為模板將是可行的方法,但即使添加數字和 const char* 的情況也不可能發生,但我收到了編譯錯誤。

no match for 'operator+=' (operand types are 'long double' and 'std::__cxx11::basic_string<char>')
   22 |         numericSum += tupleValue;
      |         ~~~~~~~~~~~^~~~~~~~~~~~~
error:   in evaluation of 'operator+=(long double, const char*)'

那么有什么方法可以修改我的代碼來解決這個問題呢? 是否有一種類似於 is_arithmetic 的簡單方法來檢測字符和字符串?

// Based on the datatype of the tupleValue, we either add, concatenate or ignore the value
template<typename T>
void interact_with_tuple(T tupleValue, long double &numericSum, string &stringConcatenation, int &argumentsIgnored){
    // Check for chars
    if (is_convertible<T*, string>::value){
        stringConcatenation += tupleValue;
    }
    // Check for strings and char pointers
    else if (is_convertible<T, string>::value){
        stringConcatenation += tupleValue;
    }
    // Check for integers and floating point numbers but exclude bools
    else if (is_arithmetic<T>::value && !is_same<T, bool>::value){
        numericSum += tupleValue;
    }   
    else{
        argumentsIgnored += 1;
    }

    cout << tupleValue << endl;
}

主函數中的代碼:

int main(){
    tuple<int32_t, bool, string, float, int> t{10, true, "Modern", 2.3f, 13}; // Example Tuple

    long double NumericSum = 0.0;
    string stringConcatenation = "";
    int argumentsIgnored = 0; // Im going to assume I don't need a long long for this

    // Iterate through Tuple
    apply([&](auto&&... args){((interact_with_tuple(args, NumericSum, stringConcatenation, argumentsIgnored)), ...);}, t); 

    cout << "NumericSum: " << NumericSum << endl;
    cout << "stringConcatenation: " << stringConcatenation << endl;
    cout << "argumentsIgnored: " << argumentsIgnored << endl;
}

您可以使用 C++17' is new compile-time conditional if constexpr 它只會編譯您需要的塊並丟棄其余的塊。

if constexpr (std::is_convertible<T*, std::string>::value){
    stringConcatenation += tupleValue;
}
// Check for strings and char pointers
else if constexpr (std::is_convertible<T, std::string>::value){
    stringConcatenation += tupleValue;
}
// Check for integers and floating point numbers but exclude bools
else if constexpr (std::is_arithmetic<T>::value && !std::is_same<T, bool>::value){
    numericSum += tupleValue;
}   
else{
    argumentsIgnored += 1;
}

現場演示: https : //godbolt.org/z/rff88hM8r

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM