我正在使用以下代碼進行原型設計。爲什麼將char *傳遞給字符串參數會產生編譯錯誤?
#include <vector>
#include <iostream>
#include <algorithm>
#include <string>
template<class container, class value> class Add {
public:
Add(){};
~Add(){};
void add_value(container& cont, value& val){
std::for_each(cont.begin(), cont.end(), [&val](value& v){v +=val;});
};
};
int main(int argc, char const *argv[])
{
Add<std::vector<std::string>, std::string> a;
std::vector<std::string> vec = {"a", "b", "c", "d"};
std::string foo= "1";
a.add_value(vec, foo); // compiles fine
a.add_value(vec, "1"); // generates an error
return 0;
}
,我得到了以下錯誤
template.cpp:28:25: error: invalid initialization of non-const reference of type ‘std::__cxx11::basic_string<char>&’ from an rvalue of type ‘std::__cxx11::basic_string<char>’
爲什麼它不可能通過一個char*
到string
說法?
據我所知,爲了將char*
轉換爲std::string
並將結果傳遞給該函數,將執行一個隱式轉換。
功能需要採取一個const引用。非const引用不能綁定到臨時對象,比如將「1」轉換爲字符串所產生的臨時對象。錯誤消息告訴你。 –
我在這裏很好奇。爲什麼非const引用不能綁定到右值? – hannibal
因爲C++標準沒有說。 –